import env from "../env";
import xhr from "../xhr";
import {
  isObject,
  isArray,
  isFunction,
  isString,
  isNumber,
  isBool,
  isInvalid,
} from "../util";
import {
  object,
  array,
  string,
  int,
  float,
  bool,
  findValue,
  deepCopy,
  delInvalidProp,
} from "../util";
import {
  toTimeString,
  toMoneyString,
  toMagicImgURL,
  getURLQuery,
  mergeURL,
} from "../util";
import { cache, session, storage } from "../util";
import COS from "cos-js-sdk-v5";

export default {
  name: "plugin-user",
  profile: null,
  provinces: [],
  citys: [],
  countys: [],
  async call(...handles) {
    let res = undefined;
    for (let handle of handles) {
      if (isFunction(handle)) res = await handle(res);
      else res = await handle;
      if (isInvalid(res)) continue;
      if (res.code !== 0) break;
    }
    return res;
  },
  async post(url, data = {}, options = {}) {
    if (url in env.xhrNodes) url = env.xhrNodes[url];
    return xhr
      .post(
        url,
        data,
        Object.assign(options, {
          api: env.xhrPrefix,
          headers: Object.assign(object(options.headers), {
            session: storage([env.key, this.name, "session"]) || "666",
          }),
        })
      )
      .then((content) => {
        let { code, msg, data } = content;
        if (code === "CanceledError") [code, msg] = [-1, ""];
        else if (code === "AxiosError") [code, msg] = [-2, ""];
        else if (code === "Error") [code, msg] = [-3, ""];
        else if (data && Object.getPrototypeOf(data) === Object.prototype)
          [code, msg, data] = [data.code, data.msg, data.data];
        return {
          code,
          msg: msg || findValue(env.xhrErrors, "code", code, "msg", ""),
          data,
        };
      });
  },
  async postother(url, data = {}, options = {}) {
    if (url in env.xhrNodes) url = env.xhrNodes[url];
    return xhr
      .post(
        url,
        data,
        Object.assign(options, {
          api: env.xhrPrefix,
          headers: Object.assign(object(options.headers), {
            session: storage([env.key, this.name, "session"]) || "666",
          }),
        })
      )
      .then((content) => {
        let { e, jd, s, data } = content;

        if (data && Object.getPrototypeOf(data) === Object.prototype)
          [e, jd, s, data] = [data.e, data.jd, data.s, data.zhou];
        return { e, jd, s, data };
      });
  },
  async getVCode() {
    let res = await this.post("/pub/vcode.get");
    let data = object(res.data);
    if (res.code === 0) res.data = { id: data.codeId, url: data.code };
    return res;
  },
  //大屏 rateScrollList
  async getEightData(year) {

    let res = await this.post("app/big/data/eight/great", {
      startTime: year?new Date(year, 0, 1).getTime():null,
      endTime: year?new Date(year+'-12-31 23:59:59').getTime():null,
    });
    return res;
  },

  async getscreenData() {
    let res = await this.post("/app/big/data/visit/count");
    return res;
  },
  async getSubmitScrollData() {
    let res = await this.post("app/big/data/event/submit");
    return res;
  },
  /**
   * 获取时间段内提交事项
   * @return {Promise<{msg, code: *, data: *}>}
   */
  async getTimeRangOrderData(params) {
    let res = await this.post("app/big/data/event/time",params);
    return res;
  },

  async getEndScrollList() {
    let res = await this.post("app/big/data/event/end");
    return res;
  },
  async getTimeoutScrollList() {
    let res = await this.post("app/big/data/event/overtime");
    return res;
  },
  async getinterviewdata() {
    let res = await this.postother("app/big/data/quarter/interview/data");
    return res;
  },
  /**
   * 按月统计年度提交的事项数量
   * @param year
   * @return {Promise<{s: *, data: *, e: *, jd: *}>}
   */
  async workOrderMonthStatistics(year) {
    let res = await this.post("/app/big/data/month/statistic?year="+year);
    return res;
  },
  // 办结率
  /**
   * 办结率
   * @param form.startTime
   * @param form.endTime
   * @param form.areaId 城市
   * @return {Promise<{msg, code: *, data: *}>}
   */
  async getRateScrollList(form={}) {
    let res = await this.post("app/big/data/completion/rate/area", form);
    return res;
  },
  async getRateScrollListcity(form = {}) {
    let res = await this.post("app/big/data/completion/rate/area", {
      areaId: isString(form.cityId) && form.cityId ? form.cityId : null,
      startTime: int(form.startTime) > 0 ? int(form.startTime) : null,
      endTime: int(form.endTime) > 0 ? int(form.endTime) : null,
      level: int(form.level) > 0 ? int(form.level) : null,
    });
    if (res.code === 0) res.data = array(res.data);
    return res;
  },

  async geteightGreatnum(eightGreat,year) {
    let res = await this.post("app/big/data/eight/great/detail", {
      eightGreatName: eightGreat,
      startTime:year?new Date(year, 0, 1).getTime():null,
      endTime:year?new Date(year+'-12-31 23:59:59').getTime():null,
    });
    return res;
  },
  async updateReply(params) {
    let res = await this.post("app/corpV3/updateReply", {
      type: params.type,
      id: params.id,
      reply: params.content,
    });
    return res;
  },
  async statisticsdata(params,year) {
    let res = await this.post("app/big/data/event/map/data/statistics", {
      tagId: params,
      startTime: year?new Date(year, 0, 1).getTime():null,
      endTime: year?new Date(year+'-12-31 23:59:59').getTime():null,
    });
    return res;
  },
  async activationfun(params) {
    let res = await this.post("admin/userAccount/activate/user", {
      ids: params.join(","),
    });
    return res;
  },
  async businessdata(params,year) {
    let res = await this.post("app/big/data/regional/business/details", {
      tagId: params.tagId,
      areaId: params.areaId || "666",
      startTime: year?new Date(year, 0, 1).getTime():null,
      endTime: year?new Date(year+'-12-31 23:59:59').getTime():null,
    });
    return res;
  },
  async getworkDynamics(params) {
    let res = await this.post("app/big/data/work/dynamics", {
      nian: params.nian,
      yue: params.yue,
    });
    return res;
  },
  async deleteCounterSignByAdmin(counterSignId){
    let res = await this.post("/govs/workOrderNew/deleteCountersignByAdmin", {
      counterSignId: counterSignId,
    });
    return res;
  },


  async getVisitsList() {
    let res = await this.post("app/big/data/visit/group");
    return res;
  },
  async getClass3List() {
    let res = await this.post("app/big/data/enterprise/classification3");
    return res;
  },

  // getMapList
  async getMapList() {
    let res = await this.post("app/big/data/standard/enterprise/map/data");
    return res;
  },
  async getvisitcities(form) {
    let res = await this.post("app/big/data/visit/cities/and/counties", {});

    return res;
  },
  async getparticularsevent(form) {
    let res = await this.post("app/big/data/particulars/of/the/event", {
      orderId: form,
    });

    return res;
  },
  async getvisitcitieone(form) {
    let res = await this.post("app/big/data/visit/cities/and/counties", {
      areaId: form,
    });

    return res;
  },

  // 其他
  async getMCode(form = {}) {
    let res = await this.post("/pub/mcode.get", {
      phone: string(form.mobile),
    });
    if (res.code === 0) {
    }
    return res;
  },

  async login(form = {}) {
    let res = await this.post(
      "/pub/login",
      {
        loginType: bool(form.sms) ? "1" : "2",
        account: bool(form.sms) ? string(form.mobile) : string(form.number),
        password: bool(form.sms) ? null : string(form.password),
        verifyCodeId: bool(form.sms) ? null : string(form.vcodeId),
        verifyCode: bool(form.sms) ? null : string(form.vcode),
        verifySms: bool(form.sms) ? string(form.mcode) : null,
      },
      {
        after: (config) =>
          storage(
            [env.key, this.name, "session"],
            () => config.data.data.session
          ),
      }
    );
    if (res.code === 0) this.profile = null;
    return res;
  },
  async logout() {
    let res = await this.post("/pub/logout");
    if (res) this.profile = null;
    if (res) storage([env.key, this.name, "session"], "");
    return res;
  },
  async uploadFile(file, type, progress) {
    let config = {};
    return this.call(
      async () => {
        let res = await this.post("/file.upload", {
          objType: findValue(env.fileTypes, "value", type, "id", ""),
          objName: file.name,
          file:file
        },{
          headers:{
            "Content-Type":"multipart/form-data"
          },
          progress:(e)=>{
            console.log('进度',e)
            if(progress){
              progress(e)
            }
          }
        });
        if (res.code === 0) config = object(res.data);
        let result = {
          ...res
        }
        if(result.data){
          result.data['name'] = res?.data?.objName
          result.data['id'] = res?.data?.objId
        }
        return result;
      },

      // async () => {
      //   let res = await this.post("/file.upload1", {
      //     objType: findValue(env.fileTypes, "value", type, "id", ""),
      //     objName: file.name,
      //   });
      //   if (res.code === 0) config = object(res.data);
      //   return res;
      // },
      // async () => {
      //   let sign = object(config.sign);
      //   let credentials = object(sign.credentials);
      //   let getAuthorization = (options, callback) =>
      //     callback({
      //       TmpSecretId: credentials.tmpSecretId,
      //       TmpSecretKey: credentials.tmpSecretKey,
      //       XCosSecurityToken: credentials.sessionToken,
      //       StartTime: sign.startTime,
      //       ExpiredTime: sign.expiredTime,
      //     });
      //   let params = delInvalidProp({
      //     Bucket: config.bucket,
      //     Region: config.region,
      //     Key: config.key,
      //     Body: file,
      //     CacheControl: type === "image" ? "public" : "no-cache",
      //     ContentDisposition:
      //       (type === "document" ? "attachment" : "inline") +
      //       ";filename*=UTF-8''" +
      //       encodeURIComponent(file.name),
      //     onProgress: isFunction(progress)
      //       ? (data) =>
      //           progress({
      //             total: int(data.total),
      //             loaded: int(data.loaded),
      //             percent: int(data.percent, 2),
      //           })
      //       : null,
      //   });
      //   let upload = (resolve) =>
      //     new COS({ getAuthorization }).putObject(params, (error, data) => {
      //       if (error) resolve({ code: error.code, msg: error.message });
      //       else resolve({ code: 0 });
      //     });
      //   return new Promise((resolve) => upload(resolve));
      // },
      // async () => {
      //   let res = await this.post("/file.upload2", {
      //     objType: findValue(env.fileTypes, "value", type, "id", ""),
      //     objName: file.name,
      //     objPath: config.key,
      //     objSize: file.size,
      //   });
      //   let data = object(res.data);
      //   if (res.code === 0) res.data = this.formatFile(res.data);
      //   return res;
      // }
    );
  },
  async setFileOpen(form = {}){
    return this.call(
      async () => {
        let res = await this.post("/file.public", {
          objId:form.id
        });
        return res;
      }
    );
  },
  formatFile(data = {}) {
    return {
      id: string(data.objId),
      type: findValue(env.fileTypes, "id", string(data.objType), "value", ""),
      name: string(data.objName).split("/").pop(),
      value: mergeURL(data.objPath, { id: string(data.objId) }),
      short: toMagicImgURL(data.objPath, 240, 240),
    };
  },
  formatUserProfile(data = {}) {
    return {
      id: string(data.userId),
      avatar: toMagicImgURL(
        mergeURL(() => data.userAvatarSysStorage.objPath, {
          id: data.userAvatar,
        }),
        120,
        120
      ),
      number: string(data.userAccount),
      name: string(data.userName),
      nick: string(data.userNickname),
      sex: findValue(env.userSexs, "id", string(data.userGender), "value", ""),
      sexText: findValue(
        env.userSexs,
        "id",
        string(data.userGender),
        "name",
        ""
      ),
      sequence: string(data.idNumber),
      mobile: string(data.userPhone),
      email: string(data.userEmail),
      role: findValue(env.userRoles, "id", string(data.userRole), "value", ""),
      roleText: findValue(
        env.userRoles,
        "id",
        string(data.userRole),
        "name",
        ""
      ),
      depments: array(data.userIdDeptRelList).map((data) => ({
        id: string(data.id),
        dept: {
          id: string(data.deptId),
          name: string(() => data.deptIdDepartment.deptName),
          province: {
            id: string(() => data.deptIdDepartment.provinceId),
            name: "",
          },
          city: {
            id: string(() => data.deptIdDepartment.cityId),
            name: "",
          },
          county: {
            id: string(() => data.deptIdDepartment.areaId),
            name: "",
          },
        },
        role: findValue(
          env.depmentRoles,
          "id",
          string(data.deptRole),
          "value",
          ""
        ),
        roleText: findValue(
          env.depmentRoles,
          "id",
          string(data.deptRole),
          "name",
          ""
        ),
        primary: findValue(
          env.depmentPrimarys,
          "id",
          string(data.deptAdmin),
          "value",
          ""
        ),
        primaryText: findValue(
          env.depmentPrimarys,
          "id",
          string(data.deptAdmin),
          "name",
          ""
        ),
        duty: string(data.deptDuty),
      })),
      nodes: array(env.userNodes).map((node) => ({
        name: node.name,
        value: node.value,
        access: array(() => data.userIdAppAuthList[0].allowApp).includes(
          findValue(env.userNodes, "value", node.value, "id", "")
        ),
      })),
      nodesText: array(() => data.userIdAppAuthList[0].allowApp)
        .map((id) => findValue(env.userNodes, "id", string(id), "name", ""))
        .join("、"),
      banned: findValue(
        env.userBanneds,
        "id",
        string(data.disableFlag),
        "value",
        ""
      ),
      bannedText: findValue(
        env.userBanneds,
        "id",
        string(data.disableFlag),
        "name",
        ""
      ),
      lastActiveAt: toTimeString(int(data.lastActive), "Y年M月D日 hh:mm"),
      lastLoginAt: toTimeString(int(data.lastLogin), "Y年M月D日 hh:mm"),
      createdAt: toTimeString(int(data.createdTime), "Y年M月D日 hh:mm"),
    };
  },
  async getUserProfile() {
    let res = await this.post("/user/profile.get");
    if (res.code === 0)
      res.data = this.profile = Object.assign(
        object(this.profile),
        this.formatUserProfile(res.data)
      );
    return res;
  },
  async setUserPassword(form = {}) {
    let res = await this.post("/user/password.set", {
      userPassword: string(form.password),
      userPasswordNew: string(form.newpassword),
    });
    if (res.code === 0) {
    }
    return res;
  },
  formatUserTask(data = {}) {
    return {
      id: string(data.taskId),
      type: findValue(
        env.userTaskTypes,
        "id",
        string(data.taskType),
        "value",
        ""
      ),
      typeText: findValue(
        env.userTaskTypes,
        "id",
        string(data.taskType),
        "name",
        ""
      ),
      startAt: toTimeString(int(data.startTime), "Y年M月D日 hh:mm:ss"),
      endAt: toTimeString(int(data.endTime), "Y年M月D日 hh:mm:ss"),
      duration: ((stime, etime) =>
        (data.duration = Math.floor(
          Math.max(etime > 0 ? etime - stime : Date.now() - stime, 0) / 1000
        )))(int(data.startTime), int(data.endTime)),
      durationText: ((duration) => {
        let hours =
          duration >= 3600 ? Math.floor(duration / 3600) + "小时" : "";
        let minutes =
          duration >= 60
            ? Math.floor((duration % 3600) / 60) + "分钟"
            : duration + "秒";
        return hours + minutes;
      })(data.duration),
      result: ((type, result) => {
        if (/^export-/i.test(type)) {
          return { type: "export", url: string(result) };
        } else if (/^import-/i.test(type)) {
          let data = object(result);
          let [success, fails, url] = [
            int(data.successCount),
            int(data.errorRow),
            string(data.errorPath),
          ];
          return {
            type: "import",
            total: success + fails,
            success,
            fails,
            url,
          };
        } else {
          return {};
        }
      })(
        findValue(env.userTaskTypes, "id", string(data.taskType), "value", ""),
        data.taskResult
      ),
      expired: int(data.endTime) + 7 * 24 * 3600 * 1000 < Date.now(),
      status: findValue(
        env.userTaskStatus,
        "id",
        string(data.taskState),
        "value",
        ""
      ),
      statusText: findValue(
        env.userTaskStatus,
        "id",
        string(data.taskState),
        "name",
        ""
      ),
      createdAt: toTimeString(int(data.createdTime), "Y年M月D日 hh:mm:ss"),
    };
  },
  async getUserTasks(form = {}) {
    let res = await this.post("/user/tasks.get", {
      taskType: findValue(env.userTaskTypes, "value", form.type, "id"),
      taskState: findValue(env.userTaskStatus, "value", form.status, "id"),
      userId: string(() => this.profile.id) || "666",
      orderBy: [{ order: "taskId", by: "desc" }],
      pageSize: isNumber(form.linage) ? form.linage : 10,
      pageNum: isNumber(form.page) ? form.page : 1,
    });
    let data = object(res.data);
    if (res.code === 0)
      res.data = {
        list: array(data.list).map((data) => this.formatUserTask(data)),
        linage: Math.max(int(data.pageSize), 1),
        page: Math.max(int(data.pageNum), 1),
        total: Math.max(int(data.numberOfElements), 0),
      };
    return res;
  },
  formatProvince(data = {}) {
    return {
      id: string(data.areaId),
      name: string(data.name),
    };
  },
  async getProvinces(form = {}) {
    let provinces = this.provinces;
    if (provinces.length > 0) return { code: 0, data: provinces };
    let res = await this.post("/provinces.get", {
      areaId_exp: [
        { exp: ">=", value: "450000" },
        { exp: "<=", value: "459999" },
      ],
      level: "1",
      orderBy: [{ order: "areaId", by: "asc" }],
      pageSize: 100,
      pageNum: 1,
    });
    let data = object(res.data);
    if (res.code === 0)
      res.data = this.provinces = array(data.list).map((data) =>
        this.formatProvince(data)
      );
    return res;
  },
  formatCity(data = {}) {
    return {
      id: string(data.areaId),
      province: {
        id: string(data.parentId),
        name:
          string(() => data.parentIdSysArea.name) ||
          string(
            () =>
              this.provinces.find(
                (province) => province.id === string(data.parentId)
              ).name
          ),
      },
      name: string(data.name),
    };
  },
  async getCitys(form = {}) {
    let citys = this.citys;
    if (citys.length > 0) return { code: 0, data: citys };
    let res = await this.post("/citys.get", {
      areaId_exp: [
        { exp: ">=", value: "450000" },
        { exp: "<=", value: "459999" },
      ],
      level: "2",
      orderBy: [{ order: "areaId", by: "asc" }],
      pageSize: 1000,
      pageNum: 1,
    });
    let data = object(res.data);
    if (res.code === 0)
      res.data = this.citys = array(data.list).map((data) =>
        this.formatCity(data)
      );
    return res;
  },
  formatCounty(data = {}) {
    return {
      id: string(data.areaId),
      city: {
        id: string(data.parentId),
        name:
          string(() => data.parentIdSysArea.name) ||
          string(
            () =>
              this.citys.find((city) => city.id === string(data.parentId)).name
          ),
      },
      name: string(data.name),
    };
  },
  async getCountys(form = {}) {
    let countys = this.countys;
    if (countys.length > 0) return { code: 0, data: countys };
    let res = await this.post("/countys.get", {
      areaId_exp: [
        { exp: ">=", value: "450000" },
        { exp: "<=", value: "459999" },
      ],
      level: "3",
      orderBy: [{ order: "areaId", by: "asc" }],
      pageSize: 10000,
      pageNum: 1,
    });
    let data = object(res.data);
    if (res.code === 0)
      res.data = this.countys = array(data.list).map((data) =>
        this.formatCounty(data)
      );
    return res;
  },
  formatAppver(data = {}) {
    return {
      id: string(data.id),
      platform: findValue(
        env.appverPlatforms,
        "id",
        string(data.platform),
        "value",
        ""
      ),
      platformText: findValue(
        env.appverPlatforms,
        "id",
        string(data.platform),
        "name",
        ""
      ),
      fileUrl: string(data.fileId)
        ? mergeURL(() => data.fileIdSysStorage.objPath, { id: data.fileId })
        : "",
      fileId:string(data?.fileIdSysStorage?.objId),
      filePublicUrl: string(data?.fileIdSysStorage?.objPublicPath || ''),
      filePage: string(data.filePage),
      version: string(data.version),
      status: findValue(
        env.appverStatus,
        "id",
        string(data.status),
        "value",
        ""
      ),
      statusText: findValue(
        env.appverStatus,
        "id",
        string(data.status),
        "name",
        ""
      ),
      createdAt: toTimeString(int(data.createTime), "Y年M月D日 hh:mm:ss"),
    };
  },
  async getAppvers(form = {}) {
    let res = await this.post("/appvers.get", {
      platform: findValue(env.appverPlatforms, "value", form.platform, "id"),
      status: findValue(env.appverStatus, "value", form.status, "id"),
      orderBy: [{ order: "id", by: "desc" }],
      pageSize: isNumber(form.linage) ? form.linage : 10,
      pageNum: isNumber(form.page) ? form.page : 1,
    });
    let data = object(res.data);
    if (res.code === 0)
      res.data = {
        list: array(data.list).map((data) => this.formatAppver(data)),
        linage: Math.max(int(data.pageSize), 1),
        page: Math.max(int(data.pageNum), 1),
        total: Math.max(int(data.numberOfElements), 0),
      };
    return res;
  },
  async addAppver(form = {}) {
    let res = await this.post("/appver.add", {
      platform: findValue(
        env.appverPlatforms,
        "value",
        form.platform,
        "id",
        ""
      ),
      fileId: string(form.fileId) || string(getURLQuery(form.fileUrl).id),
      filePage: string(form.filePage),
      version: string(form.version),
      status: findValue(env.appverStatus, "value", form.status, "id", ""),
    });
    if (res.code === 0) res.data = string(res.data);
    return res;
  },
  async setAppver(form = {}) {
    let res = await this.post("/appver.set", {
      id: string(form.id),
      platform: findValue(
        env.appverPlatforms,
        "value",
        form.platform,
        "id",
        ""
      ),
      fileId: string(form.fileId) || string(getURLQuery(form.fileUrl).id),
      filePage: string(form.filePage),
      version: string(form.version),
      status: findValue(env.appverStatus, "value", form.status, "id", ""),
    });
    if (res.code === 0) {
    }
    return res;
  },
  async delAppver(...appvers) {
    let res = await this.post("/appver.del", {
      ids: appvers.map((appver) => appver.id).join(),
    });
    if (res.code === 0) {
    }
    return res;
  },
  formatDept(data = {}) {
    return {
      id: string(data.deptId),
      type: findValue(env.deptTypes, "id", string(data.deptType), "value", ""),
      typeText: findValue(
        env.deptTypes,
        "id",
        string(data.deptType),
        "name",
        ""
      ),
      parentId: string(data.parentId),
      belongToId: string(data.belongToId),
      dept: {
        id: string(data.parentId),
        name: string(() => data.parentIdDepartment.deptName),
      },
      name: string(data.deptName),
      province: this.formatProvince(data.provinceIdSysArea),
      city: this.formatCity(data.cityIdSysArea),
      county: this.formatCounty(data.areaIdSysArea),
      depts: [],
      level: int(data.deptLevel),
      sort: int(data.deptSort),
      activated: false,
      expanded: false,
      selected: false,
      loaded: false,
    };
  },
  async getDepts(form = {}) {
    let res = await this.post("/depts.get", {
      parentId: string(form.deptId) || null,
      deptId_exp: string(form.deptIds)
        ? [{ exp: "in", value: form.deptIds.toString() ,parameterType:'Long'}]
        : null,
      deptLevel: isNumber(form.level) ? form.level : null,
      orderBy: [{ order: "deptId", by: "asc" }],
      pageSize: isNumber(form.linage) ? form.linage : 10,
      pageNum: isNumber(form.page) ? form.page : 1,
      deptName_exp: string(form.deptName)
          ? [{ exp: "like", value: form.deptName }]
          : null
    });
    let data = object(res.data);
    if (res.code === 0)
      res.data = {
        list: array(data.list).map((data) => this.formatDept(data)),
        linage: Math.max(int(data.pageSize), 1),
        page: Math.max(int(data.pageNum), 1),
        total: Math.max(int(data.numberOfElements), 0),
      };
    return res;
  },
  async addDept(form = {}) {
    let res = await this.post("/dept.add", {
      deptType: findValue(env.deptTypes, "value", form.type, "id", ""),
      parentId: string(() => form.dept.id),
      belongToId: string(() => form.belongToId),
      deptName: string(form.name),
      provinceId: string(() => form.province.id),
      cityId: string(() => form.city.id),
      areaId: string(() => form.county.id),
      deptLevel: int(form.level),
      deptSort: int(form.sort),
    });
    if (res.code === 0) res.data = string(res.data);
    return res;
  },

  async setDept(form = {}) {
    let res = await this.post("/dept.set", {
      deptId: string(form.id),
      deptType: findValue(env.deptTypes, "value", form.type, "id", ""),
      deptType_exp: string(form.type)
        ? null
        : [{ exp: "isNull", value: "666" }],
      parentId: string(() => form.dept.id),
      belongToId: string(() => form.belongToId),
      deptName: string(form.name),
      provinceId: string(() => form.province.id) || null,
      provinceId_exp: string(() => form.province.id)
        ? null
        : [{ exp: "isNull", value: "666" }],
      cityId: string(() => form.city.id) || null,
      cityId_exp: string(() => form.city.id)
        ? null
        : [{ exp: "isNull", value: "666" }],
      areaId: string(() => form.county.id) || null,
      areaId_exp: string(() => form.county.id)
        ? null
        : [{ exp: "isNull", value: "666" }],
      deptLevel: int(form.level),
      deptSort: int(form.sort),
    });
    if (res.code === 0) {
    }
    return res;
  },
  async delDept(...depts) {
    let res = await this.post("/dept.del", {
      ids: depts.map((dept) => dept.id).join(),
    });
    if (res.code === 0) {
    }
    return res;
  },
  formatDapt(data = {}) {
    return {
      id: string(data.adId),
      dapt: {
        id: string(data.parentId),
        name: string(() => data.parentIdSysAd.name),
      },
      name: string(data.name),
      dapts: [],
      level: int(data.level),
      sort: int(data.sort),
      activated: false,
      expanded: false,
      selected: false,
    };
  },
  async getDapts(form = {}) {
    let res = await this.post("/dapts.get", {
      name_exp:
        isString(form.name) && form.name
          ? [{ exp: "like", value: form.name }]
          : null,
      level: isNumber(form.level) && form.level === 1 ? form.level : null,
      level_exp:
        isNumber(form.level) && form.level === 2
          ? [{ exp: ">=", value: form.level }]
          : null,
      orderBy: [{ order: "adId", by: "desc" }],
      pageSize: isNumber(form.linage) ? form.linage : 10,
      pageNum: isNumber(form.page) ? form.page : 1,
    });
    let data = object(res.data);
    if (res.code === 0)
      res.data = {
        list: array(data.list).map((data) => this.formatDapt(data)),
        linage: Math.max(int(data.pageSize), 1),
        page: Math.max(int(data.pageNum), 1),
        total: Math.max(int(data.numberOfElements), 0),
      };
    return res;
  },
  async addDapt(form = {}) {
    let res = await this.post("/dapt.add", {
      parentId: string(() => form.dapt.id),
      name: string(form.name),
      level: int(form.level),
      sort: int(form.sort),
    });
    if (res.code === 0) res.data = string(res.data);
    return res;
  },
  async setDapt(form = {}) {
    let res = await this.post("/dapt.set", {
      adId: string(form.id),
      parentId: string(() => form.dapt.id) || null,
      parentId_exp: string(() => form.dapt.id)
        ? null
        : [{ exp: "isNull", value: "666" }],
      name: string(form.name),
      level: int(form.level),
      sort: int(form.sort),
    });
    if (res.code === 0) {
    }
    return res;
  },
  async delDapt(...dapts) {
    let res = await this.post("/dapt.del", {
      ids: dapts.map((dapt) => dapt.id).join(),
    });
    if (res.code === 0) {
    }
    return res;
  },
  formatClient(data = {}) {
    return {
      id: string(data.userId),
      avatar: toMagicImgURL(
        mergeURL(() => data.userAvatarSysStorage.objPath, {
          id: data.userAvatar,
        }),
        120,
        120
      ),
      number: string(data.userAccount),
      name: string(data.userName),
      nick: string(data.userNickname),
      sex: findValue(env.userSexs, "id", string(data.userGender), "value", ""),
      sexText: findValue(
        env.userSexs,
        "id",
        string(data.userGender),
        "name",
        ""
      ),
      sequence: string(data.idNumber),
      mobile: string(data.userPhone),
      email: string(data.userEmail),
      role: findValue(env.userRoles, "id", string(data.userRole), "value", ""),
      roleText: findValue(
        env.userRoles,
        "id",
        string(data.userRole),
        "name",
        ""
      ),
      dapments: array(data.userIdUserProfileList).map((data) =>
        this.formatClientDapment(data)
      ),
      depments: array(data.userIdDeptRelList).map((data) =>
        this.formatClientDepment(data)
      ),
      employees: [],
      helpers: [],
      nodes: array(() => data.userIdAppAuthList[0].allowApp).map((id) =>
        findValue(env.userNodes, "id", string(id), "value", "")
      ),
      nodesText: array(() => data.userIdAppAuthList[0].allowApp)
        .map((id) => findValue(env.userNodes, "id", string(id), "name", ""))
        .join("、"),
      password: "",
      banned: findValue(
        env.userBanneds,
        "id",
        string(data.disableFlag),
        "value",
        ""
      ),
      flag: findValue(
        env.userEnable,
        "id",
        string(data.activateFlag),
        "value",
        ""
      ),
      bandFlag: findValue(
        env.userEnable,
        "id",
        string(data.activateFlag),
        "name",
        ""
      ),
      bannedText: findValue(
        env.userBanneds,
        "id",
        string(data.disableFlag),
        "name",
        ""
      ),
      lastActiveAt: toTimeString(int(data.lastActive), "Y年M月D日 hh:mm"),
      lastLoginAt: toTimeString(int(data.lastLogin), "Y年M月D日 hh:mm"),
      createdAt: toTimeString(int(data.createdTime), "Y年M月D日 hh:mm"),
      sysStorageList: data.sysStorageList,
    };
  },
  async getClients(form = {}) {
    let res = await this.post("/clients.get", {
      onlySelf: ""+form.onlySelf,
      userAccount_exp:
        isString(form.number) && form.number
          ? [{ exp: "like", value: form.number }]
          : null,
      userName_exp:
        isString(form.name) && form.name
          ? [{ exp: "like", value: form.name }]
          : null,
      userGender: findValue(env.userSexs, "value", form.sex, "id"),
      userPhone_exp:
        isString(form.mobile) && form.mobile
          ? [{ exp: "like", value: form.mobile }]
          : null,
      userRole: findValue(env.userRoles, "value", form.role, "id"),
      deptIds:
        isArray(form.deptIds) && form.deptIds.length > 0
          ? form.deptIds.join()
          : isString(form.deptId)
          ? form.deptId || null
          : null,
      disableFlag: findValue(env.userBanneds, "value", form.banned, "id"),
      activateFlag: findValue(env.userEnable, "value", form.flag, "id"),

      deptRole_exp: form.deptRole?(
        form.deptRole<10?([{exp:'==',value:form.deptRole}]):null
      ):null,

      deptAdmin_exp: form.deptRole?(
        form.deptRole>10?([{exp:'==',value:form.deptRole%10}]):null
      ):null,

      orderBy: [{ order: "userId", by: "desc" }],
      pageSize: isNumber(form.linage) ? form.linage : 10,
      pageNum: isNumber(form.page) ? form.page : 1,

    });
    let data = object(res.data);
    if (res.code === 0)
      res.data = {
        list: array(data.list).map((data) => this.formatClient(data)),
        linage: Math.max(int(data.pageSize), 1),
        page: Math.max(int(data.pageNum), 1),
        total: Math.max(int(data.numberOfElements), 0),
      };
    return res;
  },
  async exportClientsHolder(form = {}) {
    let res = await this.post("/clients/holder.export", {});
    if (res.code === 0) {
    }
    return res;
  },
  async exportClientsOfficer(form = {}) {
    let res = await this.post("/clients/officer.export", {});
    if (res.code === 0) {
    }
    return res;
  },
  async addClient(form = {}) {
    let res = await this.post("/client.add", {
      userAvatar: string(getURLQuery(form.avatar).id),
      userAccount: string(form.number),
      deptId: string(form.deptId),
      userName: string(form.name),
      userGender: findValue(env.userSexs, "value", form.sex, "id", ""),
      idNumber: string(form.sequence),
      userPhone: string(form.mobile),
      userRole: findValue(env.userRoles, "value", form.role, "id", ""),
      disableFlag: findValue(env.userBanneds, "value", form.banned, "id", ""),
    });
    if (res.code === 0) res.data = string(res.data);
    return res;
  },
  async getClient(userId) {
    let res = await this.post("/client.get", { userId: string(userId) });
    if (res.code === 0) res.data = this.formatClient(res.data);
    return res;
  },
  async setClient(form = {}) {
    let res = await this.post("/client.set", {
      userId: string(form.id),
      userAvatar: string(getURLQuery(form.avatar).id),
      userAccount: string(form.number),
      userName: string(form.name),
      userRole: findValue(env.userRoles, "value", form.role, "id", ""),

      userGender: findValue(env.userSexs, "value", form.sex, "id", ""),
      idNumber: isString(form.sequence) && form.sequence ? form.sequence : null,
      idNumber_exp:
        isString(form.sequence) && form.sequence
          ? null
          : [{ exp: "isNull", value: "666" }],
      disableFlag: findValue(env.userBanneds, "value", form.banned, "id", ""),
      activateFlag: findValue(env.userEnable, "value", form.flag, "id", ""),
    });
    if (res.code === 0) {
    }
    return res;
  },
  async importClientsHolder(form = {}) {
    let res = await this.post("/clients/holder.import", { files: form.file });
    if (res.code === 0) {
    }
    return res;
  },
  async importClientsOfficer(form = {}) {
    let res = await this.post("/clients/officer.import", { files: form.file });
    if (res.code === 0) {
    }
    return res;
  },
  formatClientDapment(data = {}) {
    return {
      id: string(data.id),
      client: this.formatClient(data.userIdUserAccount),
      dapt: this.formatDapt(data.adIdSysAd),
      level: string(data.level),
      duty: string(data.duty),
    };
  },
  async addClientDapment(client = {}, dapt = {}, form = {}) {
    let res = await this.post("/client/dapment.add", {
      userId: string(client.id),
      adId: string(dapt.id),
      level: string(form.level),
      duty: string(form.duty),
    });
    if (res.code === 0) {
    }
    return res;
  },
  async setClientDapment(client = {}, dapt = {}, form = {}) {
    let res = await this.post("/client/dapment.set", {
      id: string(form.id),
      adId: string(dapt.id),
      level: isString(form.level) && form.level ? form.level : null,
      level_exp:
        isString(form.level) && form.level
          ? null
          : [{ exp: "isNull", value: "666" }],
      duty: isString(form.duty) && form.duty ? form.duty : null,
      duty_exp:
        isString(form.duty) && form.duty
          ? null
          : [{ exp: "isNull", value: "666" }],
    });
    if (res.code === 0) {
    }
    return res;
  },
  async delClientDapment(...dapments) {
    let res = await this.post("/client/dapment.del", {
      ids: dapments.map((dapment) => dapment.id).join(),
    });
    if (res.code === 0) {
    }
    return res;
  },
  formatClientDepment(data = {}) {
    return {
      id: string(data.id),
      client: this.formatClient(data.userIdUserAccount),
      dept: this.formatDept(data.deptIdDepartment),
      role: findValue(
        env.depmentRoles,
        "id",
        string(data.deptRole),
        "value",
        ""
      ),
      roleText: findValue(
        env.depmentRoles,
        "id",
        string(data.deptRole),
        "name",
        ""
      ),
      primary: findValue(
        env.depmentPrimarys,
        "id",
        string(data.deptAdmin),
        "value",
        ""
      ),
      primaryText: findValue(
        env.depmentPrimarys,
        "id",
        string(data.deptAdmin),
        "name",
        ""
      ),
      duty: string(data.deptDuty),
    };
  },
  async addClientDepment(client = {}, dept = {}, form = {}) {
    let res = await this.post("/client/depment.add", {
      userId: string(client.id),
      deptId: string(dept.id),
      deptRole: findValue(env.depmentRoles, "value", form.role, "id", ""),
      deptDuty: string(form.duty),
      deptAdmin: findValue(
        env.depmentPrimarys,
        "value",
        form.primary,
        "id",
        ""
      ),
    });
    if (res.code === 0) {
    }
    return res;
  },
  async setClientDepment(client = {}, dept = {}, form = {}) {
    let res = await this.post("/client/depment.set", {
      id: string(form.id),
      deptId: string(dept.id),
      deptRole: findValue(env.depmentRoles, "value", form.role, "id", ""),
      deptDuty: isString(form.duty) && form.duty ? form.duty : null,
      deptDuty_exp:
        isString(form.duty) && form.duty
          ? null
          : [{ exp: "isNull", value: "666" }],
      deptAdmin: findValue(
        env.depmentPrimarys,
        "value",
        form.primary,
        "id",
        ""
      ),
    });
    if (res.code === 0) {
    }
    return res;
  },
  async delClientDepment(...depments) {
    let res = await this.post("/client/depment.del", {
      ids: depments.map((depment) => depment.id).join(),
    });
    if (res.code === 0) {
    }
    return res;
  },
  async setClientMobile(client = {}, mobile) {
    let res = await this.post("/client/mobile.set", {
      userId: string(client.id),
      userPhone: string(mobile),
    });
    if (res.code === 0) {
    }
    return res;
  },
  async setClientPassword(client = {}, password) {
    let res = await this.post("/client/password.set", {
      userId: string(client.id),
      userPassword: string(password),
    });
    if (res.code === 0) {
    }
    return res;
  },
  async setClientNodes(client = {}, nodes = []) {
    let res = await this.post("/client/nodes.set", {
      userId: string(client.id),
      allowApp: array(nodes).map((node) =>
        findValue(env.userNodes, "value", string(node), "id", "")
      ),
    });
    if (res.code === 0) {
    }
    return res;
  },
  formatCompanyOfIndustry(data = {}) {
    return {
      id: string(data.id),
      name: string(data.name),
    };
  },
  async getCompanyOfIndustrys(form = {}) {
    let res = await this.post("/company/of/industrys.get", {
      name_exp:
        isString(form.name) && form.name
          ? [{ exp: "like", value: form.name }]
          : null,
      orderBy: [{ order: "id", by: "desc" }],
      pageSize: isNumber(form.linage) ? form.linage : 10,
      pageNum: isNumber(form.page) ? form.page : 1,
    });
    let data = object(res.data);
    if (res.code === 0)
      res.data = {
        list: array(data.list).map((data) =>
          this.formatCompanyOfIndustry(data)
        ),
        linage: Math.max(int(data.pageSize), 1),
        page: Math.max(int(data.pageNum), 1),
        total: Math.max(int(data.numberOfElements), 0),
      };
    return res;
  },
  async addCompanyOfIndustry(form = {}) {
    let res = await this.post("/company/of/industry.add", {
      name: string(form.name),
    });
    if (res.code === 0) {
    }
    return res;
  },
  async setCompanyOfIndustry(form = {}) {
    let res = await this.post("/company/of/industry.set", {
      id: string(form.id),
      name: string(form.name),
    });
    if (res.code === 0) {
    }
    return res;
  },
  async delCompanyOfIndustry(...industrys) {
    let res = await this.post("/company/of/industry.del", {
      ids: industrys.map((industry) => industry.id).join(),
    });
    if (res.code === 0) {
    }
    return res;
  },
  formatCompanyOfTag(data = {}) {
    return {
      id: string(data.tagId),
      name: string(data.tagName),
      sort: int(data.tagSort),
    };
  },
  async getCompanyOfTags(form = {}) {
    let res = await this.post("/company/of/tags.get", {
      tagName_exp:
        isString(form.name) && form.name
          ? [{ exp: "like", value: form.name }]
          : null,
      orderBy: [
        { order: "tagSort", by: "desc" },
        { order: "tagId", by: "desc" },
      ],
      pageSize: isNumber(form.linage) ? form.linage : 10,
      pageNum: isNumber(form.page) ? form.page : 1,
    });
    let data = object(res.data);
    if (res.code === 0)
      res.data = {
        list: array(data.list).map((data) => this.formatCompanyOfTag(data)),
        linage: Math.max(int(data.pageSize), 1),
        page: Math.max(int(data.pageNum), 1),
        total: Math.max(int(data.numberOfElements), 0),
      };
    return res;
  },
  async addCompanyOfTag(form = {}) {
    let res = await this.post("/company/of/tag.add", {
      tagName: string(form.name),
      tagSort: int(form.sort),
    });
    if (res.code === 0) {
    }
    return res;
  },
  async setCompanyOfTag(form = {}) {
    let res = await this.post("/company/of/tag.set", {
      tagId: string(form.id),
      tagName: string(form.name),
      tagSort: int(form.sort),
    });
    if (res.code === 0) {
    }
    return res;
  },
  async delCompanyOfTag(...tags) {
    let res = await this.post("/company/of/tag.del", {
      ids: tags.map((tag) => tag.id).join(),
    });
    if (res.code === 0) {
    }
    return res;
  },
  formatCompany(data = {}) {
    return {
      ...data,
      industryIds: array(data.corpIdSysIndustryList).map((x) =>x.id) || [],
      id: string(data.corpId),
      type: findValue(
        env.companyTypes,
        "id",
        string(data.corpType),
        "value",
        ""
      ),
      typeText: findValue(
        env.companyTypes,
        "id",
        string(data.corpType),
        "name",
        ""
      ),
      logo: toMagicImgURL(
        mergeURL(() => data.corpIconSysStorage.objPath, { id: data.corpIcon }),
        120,
        120
      ),
      fwxz: string(data.fwxz),
      qyxz: string(data.qyxz),
      xydm: string(data.xydm),
      name: string(data.corpName),
      code: string(data.corpCode),
      owner: string(data.corpOwner),
      size: findValue(
        env.companySizes,
        "id",
        string(data.corpSize),
        "value",
        ""
      ),
      sizeText: findValue(
        env.companySizes,
        "id",
        string(data.corpSize),
        "name",
        ""
      ),
      desc: string(() => data.corpIdCorpIntroList[0].content),
      province: this.formatProvince(data.provinceSysArea),
      city: this.formatCity(data.citySysArea),
      county: this.formatCounty(data.countySysArea),
      cert01: findValue(
        env.companyCert01s,
        "id",
        string(data.corpCert01),
        "value",
        ""
      ),
      cert01Text: findValue(
        env.companyCert01s,
        "id",
        string(data.corpCert01),
        "name",
        ""
      ),
      cert02: findValue(
        env.companyCert02s,
        "id",
        string(data.corpCert02),
        "value",
        ""
      ),
      cert02Text: findValue(
        env.companyCert02s,
        "id",
        string(data.corpCert02),
        "name",
        ""
      ),
      cert03: findValue(
        env.companyCert03s,
        "id",
        string(data.corpCert03),
        "value",
        ""
      ),
      cert03Text: findValue(
        env.companyCert03s,
        "id",
        string(data.corpCert03),
        "name",
        ""
      ),
      cert04: findValue(
        env.companyCert04s,
        "id",
        string(data.corpCert04),
        "value",
        ""
      ),
      cert04Text: findValue(
        env.companyCert04s,
        "id",
        string(data.corpCert04),
        "name",
        ""
      ),
      cert05: findValue(
        env.companyCert05s,
        "id",
        string(data.corpCert05),
        "value",
        ""
      ),
      cert05Text: findValue(
        env.companyCert05s,
        "id",
        string(data.corpCert05),
        "name",
        ""
      ),
      cert06: findValue(
        env.companyCert06s,
        "id",
        string(data.corpCert06),
        "value",
        ""
      ),
      cert06Text: findValue(
        env.companyCert06s,
        "id",
        string(data.corpCert06),
        "name",
        ""
      ),
      location: {
        lng: float(data.longitude, 6),
        lat: float(data.latitude, 6),
        coord: float(data.latitude, 6) + "," + float(data.longitude, 6),
        address: string(data.address),
        link: mergeURL("https://apis.map.qq.com/uri/v1/marker", {
          marker:
            "coord:" +
            float(data.latitude, 6) +
            "," +
            float(data.longitude, 6) +
            ";title:" +
            string(data.corpName) +
            ";addr:" +
            string(() => data.citySysArea.name) +
            string(() => data.countySysArea.name) +
            string(data.address),
        }),
      },
      industry: this.formatCompanyOfIndustry(data.industryIdSysIndustry),
      tag: this.formatCompanyOfTag(
        object(() => data.corpTagMappCorpTagMapList[0])
      ),
      depts: array(data.corpIdCorpCompetentList).map((data) =>
        this.formatDept(data.deptIdDepartment)
      ),
      staffs: array(data.corpIdCorpContactList)
        .filter((data) => string(data.type) === "1")
        .map((data) => this.formatCompanyStaff(data)),
      holders: array(data.corpIdCorpContactList)
        .filter((data) => string(data.type) === "2")
        .map((data) => this.formatCompanyHolder(data)),
      attendances: array(data.corpIdCorpSignList).map((data) =>
        this.formatAttendance(data)
      ),
      stats: {
        ordersTotal: int(data.workOrderCount),
        ordersFinishedYesTotal:
          int(data.workOrderCount) - int(data.workOrderCompleteFlag_1),
        ordersFinishedNotTotal: int(data.workOrderCompleteFlag_1),
      },
      status: findValue(
        env.companyStatus,
        "id",
        string(data.status),
        "value",
        ""
      ),
      statusText: findValue(
        env.companyStatus,
        "id",
        string(data.status),
        "name",
        ""
      ),
      creator: this.formatClient(data.createdUserUserAccount),
      createdAt: toTimeString(int(data.createdTime), "Y年M月D日 hh:mm"),
    };
  },
  async getCompanys(form = {}) {
    let res = await this.post("/companys.get", {
      corpId_exp:
        isArray(form.ids) && form.ids.length > 0
          ? [
              {
                exp: "in",
                parameterType: "Long",
                value: form.ids.join() || "666",
              },
            ]
          : null,
      corpType: findValue(env.companyTypes, "value", form.type, "id"),
      corpName_exp:
        isString(form.name) && form.name
          ? [{ exp: "like", value: form.name }]
          : null,
      corpSize: findValue(env.companySizes, "value", form.size, "id"),
      province: isString(form.provinceId) ? form.provinceId || null : null,
      city: isString(form.cityId) ? form.cityId || null : null,
      county: isString(form.countyId) ? form.countyId || null : null,
      tagId_exp:
        isString(form.tagId) && form.tagId
          ? [{ exp: "==", value: form.tagId }]
          : null,
      deptId_exp:
        isString(form.deptId) && form.deptId
          ? [{ exp: "==", value: form.deptId }]
          : null,
      corpContactUserId_exp:
        isString(form.clientId) && form.clientId
          ? [{ exp: "==", value: form.clientId }]
          : null,
      industryId:form.industryId,
      status: findValue(env.companyStatus, "value", form.status, "id"),
      orderBy: [{ order: "corpId", by: "desc" }],
      pageSize: isNumber(form.linage) ? form.linage : 10,
      pageNum: isNumber(form.page) ? form.page : 1,
    });
    let data = object(res.data);
    if (res.code === 0)
      res.data = {
        list: array(data.list).map((data) => this.formatCompany(data)),
        linage: Math.max(int(data.pageSize), 1),
        page: Math.max(int(data.pageNum), 1),
        total: Math.max(int(data.numberOfElements), 0),
      };
    return res;
  },
  async exportCompanys(form = {}) {
    let res = await this.post("/companys.export", {
      corpId_exp:
        isArray(form.ids) && form.ids.length > 0
          ? [
              {
                exp: "in",
                parameterType: "Long",
                value: form.ids.join() || "666",
              },
            ]
          : null,
      corpType: findValue(env.companyTypes, "value", form.type, "id"),
      corpName_exp:
        isString(form.name) && form.name
          ? [{ exp: "like", value: form.name }]
          : null,
      corpSize: findValue(env.companySizes, "value", form.size, "id"),
      province: isString(form.provinceId) ? form.provinceId || null : null,
      city: isString(form.cityId) ? form.cityId || null : null,
      county: isString(form.countyId) ? form.countyId || null : null,
      tagId_exp:
        isString(form.tagId) && form.tagId
          ? [{ exp: "==", value: form.tagId }]
          : null,
      deptId_exp:
        isString(form.deptId) && form.deptId
          ? [{ exp: "==", value: form.deptId }]
          : null,
      corpContactUserId_exp:
        isString(form.clientId) && form.clientId
          ? [{ exp: "==", value: form.clientId }]
          : null,
      industryId:form.industryId,
      status: findValue(env.companyStatus, "value", form.status, "id"),
      orderBy: [{ order: "corpId", by: "desc" }],
    });
    if (res.code === 0) {
    }
    return res;
  },
  async exportCompanysUsed(form = {}) {
    let res = await this.post("/companys/used.export", {
      corpId_exp:
        isArray(form.ids) && form.ids.length > 0
          ? [
              {
                exp: "in",
                parameterType: "Long",
                value: form.ids.join() || "666",
              },
            ]
          : null,
      corpType: findValue(env.companyTypes, "value", form.type, "id"),
      corpName_exp:
        isString(form.name) && form.name
          ? [{ exp: "like", value: form.name }]
          : null,
      corpSize: findValue(env.companySizes, "value", form.size, "id"),
      province: isString(form.provinceId) ? form.provinceId || null : null,
      city: isString(form.cityId) ? form.cityId || null : null,
      county: isString(form.countyId) ? form.countyId || null : null,
      tagId_exp:
        isString(form.tagId) && form.tagId
          ? [{ exp: "==", value: form.tagId }]
          : null,
      deptId_exp:
        isString(form.deptId) && form.deptId
          ? [{ exp: "==", value: form.deptId }]
          : null,
      corpContactUserId_exp:
        isString(form.clientId) && form.clientId
          ? [{ exp: "==", value: form.clientId }]
          : null,
      status: findValue(env.companyStatus, "value", form.status, "id"),
      orderBy: [{ order: "corpId", by: "desc" }],
    });
    if (res.code === 0) {
    }
    return res;
  },
  async exportCompanysAttendances(form = {}) {
    let res = await this.post("/companys/attendances.export", {
      corpId_exp:
        isArray(form.ids) && form.ids.length > 0
          ? [
              {
                exp: "in",
                parameterType: "Long",
                value: form.ids.join() || "666",
              },
            ]
          : null,
      corpType: findValue(env.companyTypes, "value", form.type, "id"),
      corpName_exp:
        isString(form.name) && form.name
          ? [{ exp: "like", value: form.name }]
          : null,
      corpSize: findValue(env.companySizes, "value", form.size, "id"),
      province: isString(form.provinceId) ? form.provinceId || null : null,
      city: isString(form.cityId) ? form.cityId || null : null,
      county: isString(form.countyId) ? form.countyId || null : null,
      tagId_exp:
        isString(form.tagId) && form.tagId
          ? [{ exp: "==", value: form.tagId }]
          : null,
      deptId_exp:
        isString(form.deptId) && form.deptId
          ? [{ exp: "==", value: form.deptId }]
          : null,
      corpContactUserId_exp:
        isString(form.clientId) && form.clientId
          ? [{ exp: "==", value: form.clientId }]
          : null,
      status: findValue(env.companyStatus, "value", form.status, "id"),
      orderBy: [{ order: "corpId", by: "desc" }],
    });
    if (res.code === 0) {
    }
    return res;
  },
  async exportCompanysOrders(form = {}) {
    let res = await this.post("/companys/orders.export", {
      corpId_exp:
        isArray(form.ids) && form.ids.length > 0
          ? [
              {
                exp: "in",
                parameterType: "Long",
                value: form.ids.join() || "666",
              },
            ]
          : null,
      corpType: findValue(env.companyTypes, "value", form.type, "id"),
      corpName_exp:
        isString(form.name) && form.name
          ? [{ exp: "like", value: form.name }]
          : null,
      corpSize: findValue(env.companySizes, "value", form.size, "id"),
      province: isString(form.provinceId) ? form.provinceId || null : null,
      city: isString(form.cityId) ? form.cityId || null : null,
      county: isString(form.countyId) ? form.countyId || null : null,
      tagId_exp:
        isString(form.tagId) && form.tagId
          ? [{ exp: "==", value: form.tagId }]
          : null,
      deptId_exp:
        isString(form.deptId) && form.deptId
          ? [{ exp: "==", value: form.deptId }]
          : null,
      corpContactUserId_exp:
        isString(form.clientId) && form.clientId
          ? [{ exp: "==", value: form.clientId }]
          : null,
      status: findValue(env.companyStatus, "value", form.status, "id"),
      orderBy: [{ order: "corpId", by: "desc" }],
    });
    if (res.code === 0) {
    }
    return res;
  },
  async addCompany(form = {}) {
    let res = await this.post("/company.add", {
      corpType: findValue(env.companyTypes, "value", form.type, "id", ""),
      corpIcon: string(getURLQuery(form.logo).id),
      corpName: string(form.name),
      corpCode: string(form.code),
      fwxz: string(form.fwxz),
      qyxz: string(form.qyxz),
      xydm: string(form.xydm),

      corpOwner: string(form.owner),
      corpSize: findValue(env.companySizes, "value", form.size, "id", ""),
      corpIntroContent: string(form.desc),
      province: string(() => form.province.id),
      city: string(() => form.city.id),
      county: string(() => form.county.id),
      longitude: float(() => form.location.lng, 6),
      latitude: float(() => form.location.lat, 6),
      address: string(() => form.location.address),
      industryName: string(() => form.industry.name),
      tagIds: string(() => form.tag.id),
      deptIds: array(form.depts)
        .map((dept) => dept.id)
        .join(),
      status: findValue(env.companyStatus, "value", form.status, "id", ""),
      industryIds: string(() => form.industryIds?.join(',')),
    });
    if (res.code === 0) res.data = string(res.data);
    return res;
  },
  async getCompany(companyId) {
    let res = await this.post("/company.get", { corpId: string(companyId) });
    if (res.code === 0) res.data = this.formatCompany(res.data);
    return res;
  },
  async setCompany(form = {}) {
    let res = await this.post("/company.set", {
      corpId: string(form.id),
      corpType: findValue(env.companyTypes, "value", form.type, "id", ""),
      corpIcon: string(getURLQuery(form.logo).id),
      corpName: string(form.name),
      fwxz: string(form.fwxz),
      xydm: string(form.xydm),
      qyxz: string(form.qyxz),
      corpCode: string(form.code),
      corpOwner: string(form.owner),
      corpSize: findValue(env.companySizes, "value", form.size, "id", ""),
      corpIntroContent: string(form.desc),
      province: string(() => form.province.id) || null,
      province_exp: string(() => form.province.id)
        ? null
        : [{ exp: "isNull", value: "666" }],
      city: string(() => form.city.id) || null,
      city_exp: string(() => form.city.id)
        ? null
        : [{ exp: "isNull", value: "666" }],
      county: string(() => form.county.id) || null,
      county_exp: string(() => form.county.id)
        ? null
        : [{ exp: "isNull", value: "666" }],
      longitude: float(() => form.location.lng, 6),
      latitude: float(() => form.location.lat, 6),
      address: string(() => form.location.address) || null,
      address_exp: string(() => form.location.address)
        ? null
        : [{ exp: "isNull", value: "666" }],
      industryName: string(() => form.industry.name),
      tagIds: string(() => form.tag.id),
      deptIds: array(form.depts)
        .map((dept) => dept.id)
        .join(),
      status: findValue(env.companyStatus, "value", form.status, "id", ""),
      industryIds: string(() => form.industryIds?.join(',')),
    });
    if (res.code === 0) {
    }
    return res;
  },
  async delCompany(...companys) {
    let res = await this.post("/company.del", {
      ids: companys.map((company) => company.id).join(),
    });
    if (res.code === 0) {
    }
    return res;
  },
  async setCompanysStatus(companys = [], status) {
    let res = await this.post("/company/status.set", {
      corpIds: array(companys)
        .map((company) => string(company.id))
        .join(),
      status: findValue(env.companyStatus, "value", string(status), "id", ""),
    });
    if (res.code === 0) {
    }
    return res;
  },
  async importCompanys(form = {}) {
    let res = await this.post("/companys.import", { files: form.file });
    if (res.code === 0) {
    }
    return res;
  },
  formatCompanyStaff(data = {}) {
    return {
      id: string(data.id),
      company: {
        id: string(data.corpId),
        name: string(() => data.corpIdCorpDetail.corpName),
      },
      client: this.formatClient(data.userIdUserAccount),
      duty: string(data.duty),
    };
  },
  async addCompanyStaff(company = {}, client = {}, form = {}) {
    let res = await this.post("/company/staff.add", {
      type: "1",
      corpId: string(company.id),
      userId: string(client.id),
      duty: string(form.duty),
    });
    if (res.code === 0) {
    }
    return res;
  },
  async delCompanyStaff(...staffs) {
    let res = await this.post("/company/staff.del", {
      ids: staffs.map((staff) => staff.id).join(),
    });
    if (res.code === 0) {
    }
    return res;
  },
  formatCompanyHolder(data = {}) {
    return {
      id: string(data.id),
      company: {
        id: string(data.corpId),
        name: string(() => data.corpIdCorpDetail.corpName),
      },
      client: this.formatClient(data.userIdUserAccount),
      duty: string(data.duty),
    };
  },
  async addCompanyHolder(company = {}, client = {}, form = {}) {
    let res = await this.post("/company/holder.add", {
      type: "2",
      corpId: string(company.id),
      userId: string(client.id),
      duty: string(form.duty),
    });
    if (res.code === 0) {
    }
    return res;
  },
  async delCompanyHolder(...holders) {
    let res = await this.post("/company/holder.del", {
      ids: holders.map((holder) => holder.id).join(),
    });
    if (res.code === 0) {
    }
    return res;
  },
  formatDemand(data = {}) {
    return {
      id: string(data.id),
      company: this.formatCompany(data.corpIdCorpDetail),
      type: findValue(env.demandTypes, "id", string(data.type), "value", ""),
      typeText: findValue(env.demandTypes, "id", string(data.type), "name", ""),
      title: string(data.title),
      content: string(data.content),
      files: string(data.attachment)
        .split(",")
        .map((objId) =>
          this.formatFile(
            object(() =>
              array(data.sysStorageList).find((data) => data.objId === objId)
            )
          )
        )
        .filter((file) => file.id && file.type),
      contacts: {
        name: string(data.contactName),
        mobile: string(data.contactPhone),
      },
      records: array(data.demandIdCorpDemandReList).map((data) => ({
        id: string(data.id),
        type: findValue(
          env.demandRecordTypes,
          "id",
          string(data.type),
          "value",
          ""
        ),
        typeText: findValue(
          env.demandRecordTypes,
          "id",
          string(data.type),
          "name",
          ""
        ),
        content: string(data.content),
        creator: this.formatClient(data.userIdUserAccount),
        createdAt: toTimeString(int(data.createdTime), "Y年M月D日 hh:mm"),
      })),
      views: int(data.hits),
      approved: findValue(
        env.demandApproveds,
        "id",
        string(data.status),
        "value",
        ""
      ),
      approvedText: findValue(
        env.demandApproveds,
        "id",
        string(data.status),
        "name",
        ""
      ),
      status: findValue(
        env.demandStatus,
        "id",
        string(data.demandState),
        "value",
        ""
      ),
      statusText: findValue(
        env.demandStatus,
        "id",
        string(data.demandState),
        "name",
        ""
      ),
      creator: this.formatClient(data.userIdUserAccount),
      createdAt: toTimeString(int(data.createdTime), "Y年M月D日 hh:mm"),
    };
  },
  async getDemands(form = {}) {
    let res = await this.post("/demands.get", {
      corpId: string(form.companyId) || null,
      corpName_exp:
        isString(form.companyName) && form.companyName
          ? [{ exp: "like", value: form.companyName }]
          : null,
      type: findValue(env.demandTypes, "value", form.type, "id"),
      title_exp:
        isString(form.title) && form.title
          ? [{ exp: "like", value: form.title }]
          : null,
      status: findValue(env.demandApproveds, "value", form.approved, "id"),
      demandState: findValue(env.demandStatus, "value", form.status, "id"),
      orderBy: [{ order: "id", by: "desc" }],
      pageSize: isNumber(form.linage) ? form.linage : 10,
      pageNum: isNumber(form.page) ? form.page : 1,
    });
    let data = object(res.data);
    if (res.code === 0)
      res.data = {
        list: array(data.list).map((data) => this.formatDemand(data)),
        linage: Math.max(int(data.pageSize), 1),
        page: Math.max(int(data.pageNum), 1),
        total: Math.max(int(data.numberOfElements), 0),
      };
    return res;
  },
  async getDemand(demandId) {
    let res = await this.post("/demand.get", { id: string(demandId) });
    if (res.code === 0) res.data = this.formatDemand(res.data);
    return res;
  },
  async setDemand(form = {}) {
    let res = await this.post("/demand.set", {
      id: string(form.id),
      status: findValue(env.demandApproveds, "value", form.approved, "id"),
    });
    if (res.code === 0) {
    }
    return res;
  },
  async delDemand(...demands) {
    let res = await this.post("/demand.del", {
      ids: demands.map((demand) => demand.id).join(),
    });
    if (res.code === 0) {
    }
    return res;
  },
  formatDemandRecord(data = {}) {
    return {
      id: string(data.id),
      type: findValue(
        env.demandRecordTypes,
        "id",
        string(data.type),
        "value",
        ""
      ),
      typeText: findValue(
        env.demandRecordTypes,
        "id",
        string(data.type),
        "name",
        ""
      ),
      content: string(data.content),
      creator: this.formatClient(data.userIdUserAccount),
      createdAt: toTimeString(int(data.createdTime), "Y年M月D日 hh:mm"),
    };
  },
  async getDemandRecords(form = {}) {
    let res = await this.post("/demand/records.get", {
      demandId: string(form.demandId) || "666",
      orderBy: [{ order: "id", by: "desc" }],
      pageSize: isNumber(form.linage) ? form.linage : 10,
      pageNum: isNumber(form.page) ? form.page : 1,
    });
    let data = object(res.data);
    if (res.code === 0)
      res.data = {
        list: array(data.list).map((data) => this.formatDemandRecord(data)),
        linage: Math.max(int(data.pageSize), 1),
        page: Math.max(int(data.pageNum), 1),
        total: Math.max(int(data.numberOfElements), 0),
      };
    return res;
  },
  async delDemandRecord(...records) {
    let res = await this.post("/demand/record.del", {
      ids: records.map((record) => record.id).join(),
    });
    if (res.code === 0) {
    }
    return res;
  },
  formatProduct(data = {}) {
    return {
      id: string(data.id),
      company: this.formatCompany(data.corpIdCorpDetail),
      avatar: toMagicImgURL(
        mergeURL(() => data.prodCoverSysStorage.objPath, {
          id: data.prodCover,
        }),
        120,
        120
      ),
      name: string(data.prodName),
      desc: string(data.prodIntro),
      sort: int(data.sort),
    };
  },
  async getProducts(form = {}) {
    let res = await this.post("/products.get", {
      corpId: string(form.companyId) || null,
      orderBy: [
        { order: "sort", by: "desc" },
        { order: "id", by: "desc" },
      ],
      pageSize: isNumber(form.linage) ? form.linage : 10,
      pageNum: isNumber(form.page) ? form.page : 1,
    });
    let data = object(res.data);
    if (res.code === 0)
      res.data = {
        list: array(data.list).map((data) => this.formatProduct(data)),
        linage: Math.max(int(data.pageSize), 1),
        page: Math.max(int(data.pageNum), 1),
        total: Math.max(int(data.numberOfElements), 0),
      };
    return res;
  },
  async getProduct(productId) {
    let res = await this.post("/product.get", { id: string(productId) });
    if (res.code === 0) res.data = this.formatProduct(res.data);
    return res;
  },
  formatFeedback(data = {}) {
    return {
      id: string(data.id),
      company: this.formatCompany(data.corpIdCorpDetail),
      type: findValue(env.feedbackTypes, "id", string(data.type), "value", ""),
      typeText: findValue(
        env.feedbackTypes,
        "id",
        string(data.type),
        "name",
        ""
      ),
      title: string(data.title),
      content: string(data.content),
      files: string(data.attachment)
        .split(",")
        .map((objId) =>
          this.formatFile(
            object(() =>
              array(data.sysStorageList).find((data) => data.objId === objId)
            )
          )
        )
        .filter((file) => file.id && file.type),
      holder: this.formatClient(data.relUserUserAccount),
      creator: this.formatClient(data.userIdUserAccount),
      createdAt: toTimeString(int(data.createdTime), "Y年M月D日 hh:mm"),
    };
  },
  async getFeedbacks(form = {}) {
    let res = await this.post("/feedbacks.get", {
      corpId: string(form.companyId) || null,
      corpName_exp:
        isString(form.companyName) && form.companyName
          ? [{ exp: "like", value: form.companyName }]
          : null,
      type: findValue(env.feedbackTypes, "value", form.type, "id"),
      title_exp:
        isString(form.title) && form.title
          ? [{ exp: "like", value: form.title }]
          : null,
      orderBy: [{ order: "id", by: "desc" }],
      pageSize: isNumber(form.linage) ? form.linage : 10,
      pageNum: isNumber(form.page) ? form.page : 1,
    });
    let data = object(res.data);
    if (res.code === 0)
      res.data = {
        list: array(data.list).map((data) => this.formatFeedback(data)),
        linage: Math.max(int(data.pageSize), 1),
        page: Math.max(int(data.pageNum), 1),
        total: Math.max(int(data.numberOfElements), 0),
      };
    return res;
  },
  formatAttendance(data = {}) {
    return {
      id: string(data.id),
      company: {
        id: string(data.corpId),
        name: string(() => data.corpIdCorpDetail.corpName),
      },
      client: this.formatClient(data.userIdUserAccount),
      startLocation: {
        lng: float(() => data.arrivalLocation.split(",")[1], 6),
        lat: float(() => data.arrivalLocation.split(",")[0], 6),
        coord: string(data.arrivalLocation),
        address: "",
        link: mergeURL("https://apis.map.qq.com/uri/v1/marker", {
          marker:
            "coord:" +
            float(() => data.arrivalLocation.split(",")[0], 6) +
            "," +
            float(() => data.arrivalLocation.split(",")[1], 6) +
            ";title:" +
            string(() => data.corpIdCorpDetail.corpName) +
            ";addr:" +
            toTimeString(int(data.arrivalTime), "Y年M月D日 hh:mm"),
        }),
      },
      startTime: int(data.arrivalTime),
      startAt: toTimeString(int(data.arrivalTime), "Y年M月D日 hh:mm"),
      endLocation: {
        lng: float(() => data.departureLocation.split(",")[1], 6),
        lat: float(() => data.departureLocation.split(",")[0], 6),
        coord: string(data.departureLocation),
        address: "",
        link: mergeURL("https://apis.map.qq.com/uri/v1/marker", {
          marker:
            "coord:" +
            float(() => data.departureLocation.split(",")[0], 6) +
            "," +
            float(() => data.departureLocation.split(",")[1], 6) +
            ";title:" +
            string(() => data.corpIdCorpDetail.corpName) +
            ";addr:" +
            toTimeString(int(data.departureTime), "Y年M月D日 hh:mm"),
        }),
      },
      endTime: int(data.departureTime),
      endAt: toTimeString(int(data.departureTime), "Y年M月D日 hh:mm"),
      files: string(data.attachment)
        .split(",")
        .map((objId) =>
          this.formatFile(
            object(() =>
              array(data.sysStorageList).find((data) => data.objId === objId)
            )
          )
        )
        .filter((file) => file.id && file.type),
    };
  },
  async getAttendances(form = {}) {
    let res = await this.post("/attendances.get", {
      corpId: isString(form.companyId) ? form.companyId || null : null,
      userId: isString(form.clientId) ? form.clientId || null : null,
      orderBy: [{ order: "id", by: "desc" }],
      pageSize: isNumber(form.linage) ? form.linage : 10,
      pageNum: isNumber(form.page) ? form.page : 1,
    });
    let data = object(res.data);
    if (res.code === 0)
      res.data = {
        list: array(data.list).map((data) => this.formatAttendance(data)),
        linage: Math.max(int(data.pageSize), 1),
        page: Math.max(int(data.pageNum), 1),
        total: Math.max(int(data.numberOfElements), 0),
      };
    return res;
  },
  async delAttendance(...attendances) {
    let res = await this.post("/attendance.del", {
      ids: attendances.map((attendance) => attendance.id).join(),
    });
    if (res.code === 0) {
    }
    return res;
  },
  formatOrderOfTag(data = {}) {
    return {
      id: string(data.tagId),
      name: string(data.tagName),
      sort: int(data.tagSort),
      eightGreat: string(data.eightGreat),
      parentId: string(data.parentId),
    };
  },
  async getOrderOfTags(form = {}) {
    let res = await this.post("/order/of/tags.get", {
      orderBy: [
        { order: "tagSort", by: "desc" },
        { order: "tagId", by: "desc" },
      ],
      pageSize: isNumber(form.linage) ? form.linage : 10,
      pageNum: isNumber(form.page) ? form.page : 1,
    });
    let data = object(res.data);
    if (res.code === 0)
      res.data = {
        list: array(data.list).map((data) => this.formatOrderOfTag(data)),
        linage: Math.max(int(data.pageSize), 1),
        page: Math.max(int(data.pageNum), 1),
        total: Math.max(int(data.numberOfElements), 0),
      };
    return res;
  },
  async addOrderOfTag(form = {}) {
    let res = await this.post("/order/of/tag.add", {
      tagName: string(form.name),
      tagSort: int(form.sort),
      eightGreat: string(form.eightGreat),
    });
    if (res.code === 0) {
    }
    return res;
  },
  async setOrderOfTag(form = {}) {
    let res = await this.post("/order/of/tag.set", {
      tagId: string(form.id),
      tagName: string(form.name),
      tagSort: int(form.sort),
      eightGreat: string(form.eightGreat),
    });
    if (res.code === 0) {
    }
    return res;
  },
  async delOrderOfTag(...tags) {
    let res = await this.post("/order/of/tag.del", {
      ids: tags.map((tag) => tag.id).join(),
    });
    if (res.code === 0) {
    }
    return res;
  },
  formatOrder(data = {}) {
    // console.log(data.userIdUserAccount);
    if (data.userIdUserAccount == undefined) {
      data.userIdUserAccount = {};
    }
    console.log(data.orderId);
    return {
      nodeId: string(data.nodeId),
      bjlx: string(data.bjlx),
      bcqk: string(data.bcqk),
      id: string(data.orderId),
      level: string(data.level),
      tags: array(data.workTagMappWorkTagMapList).map((data) =>
        this.formatOrderOfTag(data)
      ),
      company: this.formatCompany(data.corpIdCorpDetail),
      fwxz: string(data.fwxz),
      title: string(data.title),
      content: string(data.content),
      files: string(data.attachment)
        .split(",")
        .map((objId) =>
          this.formatFile(
            object(() =>
              array(data.sysStorageList).find((data) => data.objId === objId)
            )
          )
        )
        .filter((file) => file.id && file.type),
      tracks: array(data.orderIdWorkFlowList).map((data) => ({
        id: string(data.nodeId),
        orderId: string(data.orderId),
        isAdmin: string(data.isAdmin),
        type: findValue(
          env.orderTrackTypes,
          "id",
          string(data.nodeType),
          "value",
          ""
        ),
        typeText: findValue(
          env.orderTrackTypes,
          "id",
          string(data.nodeType),
          "name",
          ""
        ),
        content: string(data.nodeAnnotate),
        files: string(data.attachment)
          .split(",")
          .map((objId) =>
            this.formatFile(
              object(() =>
                array(data.sysStorageList).find((data) => data.objId === objId)
              )
            )
          )
          .filter((file) => file.id && file.type),
        dept: this.formatDept(data.deptIdDepartment),
        handler: this.formatClient(data.userIdUserAccount),
        copytos: array(data.flowIdWorkCcList).map((data) =>
          this.formatClient(data.userIdUserAccount)
        ),
        signs: array(data.flowIdWorkCountersignList).map((data) => ({
          id: string(data.id),
          type: findValue(
            env.orderTrackSignTypes,
            "id",
            string(data.type),
            "value",
            ""
          ),
          typeText: findValue(
            env.orderTrackSignTypes,
            "id",
            string(data.type),
            "name",
            ""
          ),
          content: string(data.annotate),
          files: string(data.attachment)
            .split(",")
            .map((objId) =>
              this.formatFile(
                object(() =>
                  array(data.sysStorageList).find(
                    (data) => data.objId === objId
                  )
                )
              )
            )
            .filter((file) => file.id && file.type),
          replyContent: string(data.replyAnnotate),
          replyFiles: string(data.replyAttachment)
            .split(",")
            .map((objId) =>
              this.formatFile(
                object(() =>
                  array(data.sysStorageListReply).find(
                    (data) => data.objId === objId
                  )
                )
              )
            )
            .filter((file) => file.id && file.type),
          dept: this.formatDept(data.deptIdDepartment),
          handler: this.formatClient(data.userIdUserAccount),
          isAdmin: string(data.isAdmin),
          stime: int(data.endTime - data.startTime),

          duration: ((stime, etime, duration) => {
            if (stime > 0 && etime > 0)
              duration = Math.ceil(Math.max((etime - stime) / 60000, 0));
            else if (stime > 0)
              duration = Math.ceil(Math.max((Date.now() - stime) / 60000, 0));
            let days =
              duration >= 1440 ? Math.floor(duration / 1440) + "天" : "";
            let hours =
              duration >= 60 ? Math.floor((duration % 1440) / 60) + "小时" : "";
            let minutes =
              duration >= 0 ? Math.floor(duration % 60) + "分钟" : "";
            return days + hours + minutes;
          })(int(data.startTime), int(data.endTime), 0),
          finished: findValue(
            env.orderTrackSignFinisheds,
            "id",
            string(data.status),
            "value",
            ""
          ),
          finishedText: findValue(
            env.orderTrackSignFinisheds,
            "id",
            string(data.status),
            "name",
            ""
          ),
          finishedAt: toTimeString(int(data.endTime), "Y年M月D日 hh:mm"),
          createdAt: toTimeString(int(data.startTime), "Y年M月D日 hh:mm"),
        })),
        handling: findValue(
          env.orderTrackHandlings,
          "id",
          string(data.returnFlag),
          "value",
          ""
        ),
        handlingText: findValue(
          env.orderTrackHandlings,
          "id",
          string(data.returnFlag),
          "name",
          ""
        ),
        finished: findValue(
          env.orderTrackFinisheds,
          "id",
          string(data.nodeState),
          "value",
          ""
        ),
        finishedText: findValue(
          env.orderTrackFinisheds,
          "id",
          string(data.nodeState),
          "name",
          ""
        ),

        finishedAt: toTimeString(int(data.completeTime), "Y年M月D日 hh:mm"),
        countdown: int(data.createdTime) + 86400 * 1000 * 3,
        countdownAt: ((countdown) => {
          let value = Math.ceil(Math.max(countdown - Date.now(), 0) / 1000);
          let days = Math.floor(value / 86400);
          let hours = Math.floor((value % 86400) / 3600);
          let minutes = Math.floor((value % 3600) / 60);
          let seconds = Math.floor(value % 60);
          let text =
            days + "天" + hours + "小时" + minutes + "分钟" + seconds + "秒";
          return value > 0
            ? text
                .replace("0天0小时0分钟", "")
                .replace("0天0小时", "")
                .replace("0天", "")
            : "";
        })(int(data.createdTime) + 86400 * 1000 * 3),
        createdAt: toTimeString(int(data.createdTime), "Y年M月D日 hh:mm"),
      })),
      userIdDeptRelList: data.userIdUserAccount.userIdDeptRelList
        ? data.userIdUserAccount.userIdDeptRelList
        : "",
      dept: this.formatDept(data.deptIdDepartment),
      hand: this.formatDept(data.createDeptDepartment),
      handler: this.formatClient(data.handlerIdUserAccount),
      evaluated: findValue(
        env.orderEvaluateds,
        "id",
        string(data.evaluationFlag),
        "value",
        ""
      ),
      evaluatedText: findValue(
        env.orderEvaluateds,
        "id",
        string(data.evaluationFlag),
        "name",
        ""
      ),
      evaluatedStars: int(() => data.orderIdWorkEvaluationList[0].grade),
      evaluatedContent: string(() => data.orderIdWorkEvaluationList[0].content),
      evaluatedCreator: this.formatClient(
        object(() => data.orderIdWorkEvaluationList[0].reviewerUserAccount)
      ),
      finishedAt: toTimeString(int(data.completeTime), "Y年M月D日 hh:mm"),
      finishedContent: string(data.completeContent),
      status: findValue(
        env.orderStatus,
        "id",
        string(data.status),
        "value",
        ""
      ),
      statusText: findValue(
        env.orderStatus,
        "id",
        string(data.status),
        "name",
        ""
      ),
      creator: this.formatClient(data.userIdUserAccount),
      createdAt: toTimeString(int(data.createdTime), "Y年M月D日 hh:mm"),
      tag2: data.tag2,
      money: int(data.money) || null,
      orderContract: string(data.orderContract),
      contractPhone: string(data.contractPhone),
      getOrderTime :data.getOrderTime?new Date(int(data.getOrderTime)):null,
      getOrderTimeStr : data.getOrderTime?new Date(int(data.getOrderTime)).formatDate('yyyy-MM-dd hh:mm:ss'):null,
      impact: data.impact || null,
      wtly: string(data.wtly),
    };
  },
  async getOrders(form = {}) {
    let res = await this.post("/orders.get", {
      orderId_exp:
        isArray(form.ids) && form.ids.length > 0
          ? [
              {
                exp: "in",
                parameterType: "Long",
                value: form.ids.join() || "666",
              },
            ]
          : null,
      tag2_exp:
          isString(form.tag2) && form.tag2
              ? [{ exp: "like", value: form.tag2 }]
              : null,
      tagId_exp:
        isString(form.tagId) && form.tagId
          ? [{ exp: "==", value: form.tagId }]
          : null,
      corpId: isString(form.companyId) ? form.companyId || null : null,
      corpId_exp:
        isArray(form.corpIds) && form.corpIds
          ? [{ exp: "in", value: form.corpIds.join(','),parameterType: "Long" }]
          : null,
      corpName_exp:
        isString(form.companyName) && form.companyName
          ? [{ exp: "like", value: form.companyName }]
          : null,
      corpCity_exp:
          isString(form.companyCityId) && form.companyCityId
              ? [{ exp: "==", value: form.companyCityId }]
              : null,
      corpCounty_exp:
          isString(form.companyCountyId) && form.companyCountyId
              ? [{ exp: "==", value: form.companyCountyId }]
              : null,
      title_exp:
        isString(form.title) && form.title
          ? [{ exp: "like", value: form.title }]
          : null,
      content_exp:
        isString(form.content) && form.content
          ? [{ exp: "like", value: form.content }]
          : null,
      deptId: isString(form.deptId) ? form.deptId || null : null,
      createDept: isString(form.handId) ? form.handId || null : null,
      level_exp:
        isString(form.level) && form.level
          ? [{ exp: "==", value: form.level }]
          : null,
      fwxz_exp:
        isString(form.fwxz) && form.fwxz
          ? [{ exp: "==", value: form.fwxz }]
          : null,
      evaluationFlag: findValue(
        env.orderEvaluateds,
        "value",
        form.evaluated,
        "id"
      ),
      // jbdwId: form.jbdwId,
      jbdwId: (form.jbdwId && form.jbdwId.length > 0) ? form.jbdwId.toString() : null,
      status: findValue(env.orderStatus, "value", form.status, "id"),
      orderBy: [{ order: "orderId", by: "desc" }],
      pageSize: isNumber(form.linage) ? form.linage : 10,
      pageNum: isNumber(form.page) ? form.page : 1,
      createdTimeStart: form.createdTimeStart ?? null,
      createdTimeEnd: form.createdTimeEnd ?? null,
      completeTimeStart: form.completeTimeStart ?? null,
      completeTimeEnd: form.completeTimeEnd ?? null,
    });
    let data = object(res.data);
    if (res.code === 0)
      res.data = {
        list: array(data.list).map((data) => this.formatOrder(data)),
        linage: Math.max(int(data.pageSize), 1),
        page: Math.max(int(data.pageNum), 1),
        total: Math.max(int(data.numberOfElements), 0),
      };
    return res;
  },
  async importOrders(form = {}) {
    let res = await this.post("/orders.import", { files: form.file });
    if (res.code === 0) {
    }
    return res;
  },
  async importToBackOrders(form = {}) {
    let res = await this.post("/orders.importToBack", { files: form.file });
    if (res.code === 0) {
    }
    return res;
  },
  async getCbone(data) {
    let res = await this.post("/app/workUrging/urging", {
      type: string(data.type),
      transactionId: string(data.zId),
    });
    // if (res.code === 0) res.data = this.formatOrder(res.data);
    return res;
  },
  async getOrder(orderId) {
    let res = await this.post("/order.get", { orderId: string(orderId) });
    if (res.code === 0) res.data = this.formatOrder(res.data);
    return res;
  },
  async setOrder(form = {}) {
    let res = await this.post("/order.set", {
      money: string(form.money),
      orderId: string(form.id),
      workTags: array(form.tags)
        .map((tag) => tag.id)
        .join(),
      title: string(form.title),
      fwxz: string(form.fwxz),
      content: string(form.content),
      tag2: string(form.tag2 || undefined),
      impact: string(form.impact || undefined),
      corpId: string(() => form.company.id),
      level: string(form.lev || form.level),
      xcbj: string(form.xcbj),
      wtly: string(form.wtly),
      orderContract: string(form.orderContract),
      contractPhone: string(form.contractPhone),
      getOrderTime: form.getOrderTime?.getTime() || null,
    });
    if (res.code === 0) {
    }
    return res;
  },
  async setOrderManager(form = {}) {
    let res = await this.post("/admin/workOrder/workOrderEditManager", {
      money: string(form.money),
      orderId: string(form.id),
      workTags: array(form.tags)
        .map((tag) => tag.id)
        .join(),
      title: string(form.title),
      fwxz: string(form.fwxz),
      content: string(form.content),
      tag2: string(form.tag2 || undefined),
      impact: string(form.impact || undefined),
      corpId: string(() => form.company.id),
      level: string(form.lev || form.level),
      xcbj: string(form.xcbj),
      wtly: string(form.wtly),
      orderContract: string(form.orderContract),
      contractPhone: string(form.contractPhone),
      getOrderTime: form.getOrderTime?.getTime() || null,
    });
    if (res.code === 0) {
    }
    return res;
  },
  async delOrder(...orders) {
    let res = await this.post("/order.del", {
      ids: orders.map((order) => order.id).join(),
    });
    if (res.code === 0) {
    }
    return res;
  },
  async exportOrders(form = {}) {
    let res = await this.post("/orders.export", {
      level_exp:
        isString(form.level) && form.level
          ? [{ exp: "==", value: form.level }]
          : null,
      fwxz_exp:
        isString(form.fwxz) && form.fwxz
          ? [{ exp: "==", value: form.fwxz }]
          : null,
      tag2_exp:
          isString(form.tag2) && form.tag2
              ? [{ exp: "like", value: form.tag2 }]
              : null,
      orderId_exp:
        isArray(form.ids) && form.ids.length > 0
          ? [
              {
                exp: "in",
                parameterType: "Long",
                value: form.ids.join() || "666",
              },
            ]
          : null,
      tagId_exp:
        isString(form.tagId) && form.tagId
          ? [{ exp: "==", value: form.tagId }]
          : null,
      corpId: isString(form.companyId) ? form.companyId || null : null,

      corpId_exp: isArray(form.corpIds) && form.corpIds
        ? [{ exp: "in", value: form.corpIds.join(','),parameterType: "Long" }]
        : null,
      corpName_exp:
        isString(form.companyName) && form.companyName
          ? [{ exp: "like", value: form.companyName }]
          : null,
      corpCity_exp:
          isString(form.companyCityId) && form.companyCityId
              ? [{ exp: "==", value: form.companyCityId }]
              : null,
      corpCounty_exp:
          isString(form.companyCountyId) && form.companyCountyId
              ? [{ exp: "==", value: form.companyCountyId }]
              : null,
      title_exp:
        isString(form.title) && form.title
          ? [{ exp: "like", value: form.title }]
          : null,
      content_exp:
        isString(form.content) && form.content
          ? [{ exp: "like", value: form.content }]
          : null,
      deptId: isString(form.deptId) ? form.deptId || null : null,
      evaluationFlag: findValue(
        env.orderEvaluateds,
        "value",
        form.evaluated,
        "id"
      ),
      status: findValue(env.orderStatus, "value", form.status, "id"),
      orderBy: [{ order: "orderId", by: "desc" }],
      createdTimeStart: form.createdTimeStart ?? null,
      createdTimeEnd: form.createdTimeEnd ?? null,
      completeTimeStart: form.completeTimeStart ?? null,
      completeTimeEnd: form.completeTimeEnd ?? null,
      // jbdwId: form.jbdwId ? form.jbdwId : null,
      jbdwId: (form.jbdwId && form.jbdwId.length > 0) ? form.jbdwId.toString() : null,
    });
    if (res.code === 0) {
    }
    return res;
  },
  formatArticleOfTag(data = {}) {
    return {
      id: string(data.tagId),
      tag: {
        id: string(data.parentId),
        name: string(() => data.parentIdArticleTag.tagName),
      },
      name: string(data.tagName),
      tags: [],
      level: 0,
      sort: int(data.tagSort),
      activated: false,
      expanded: false,
      selected: false,
    };
  },
  async getArticleOfTags(form = {}) {
    let res = await this.post("/article/of/tags.get", {
      orderBy: [
        { order: "tagSort", by: "desc" },
        { order: "tagId", by: "asc" },
      ],
      pageSize: isNumber(form.linage) ? form.linage : 10,
      pageNum: isNumber(form.page) ? form.page : 1,
    });
    let data = object(res.data);
    if (res.code === 0)
      res.data = {
        list: array(data.list).map((data) => this.formatArticleOfTag(data)),
        linage: Math.max(int(data.pageSize), 1),
        page: Math.max(int(data.pageNum), 1),
        total: Math.max(int(data.numberOfElements), 0),
      };
    return res;
  },
  async addArticleOfTag(form = {}) {
    let res = await this.post("/article/of/tag.add", {
      parentId: string(() => form.tag.id),
      tagName: string(form.name),
      tagSort: int(form.sort),
    });
    if (res.code === 0) res.data = string(res.data);
    return res;
  },
  async setArticleOfTag(form = {}) {
    let res = await this.post("/article/of/tag.set", {
      tagId: string(form.id),
      parentId: string(() => form.tag.id),
      tagName: string(form.name),
      tagSort: int(form.sort),
    });
    if (res.code === 0) {
    }
    return res;
  },
  async delArticleOfTag(...tags) {
    let res = await this.post("/article/of/tag.del", {
      ids: tags.map((tag) => tag.id).join(),
    });
    if (res.code === 0) {
    }
    return res;
  },
  formatArticle(data = {}) {
    return {
      id: string(data.articleId),
      type: findValue(
        env.articleTypes,
        "id",
        string(
          () =>
            array(data.articleTagMappArticleTagMapList).find(
              (data) => string(data.parentId) === ""
            ).tagId
        ),
        "value",
        ""
      ),
      typeText: findValue(
        env.articleTypes,
        "id",
        string(
          () =>
            array(data.articleTagMappArticleTagMapList).find(
              (data) => string(data.parentId) === ""
            ).tagId
        ),
        "name",
        ""
      ),
      banner: data.articleCover?env.xhrPrefix + "/user/sysStorage/getFile/" + data.articleCover+"?id="+data.articleCover:null,
      // banner: toMagicImgURL(
      //   mergeURL(() => data.articleCoverSysStorage.objPath, {
      //     id: data.articleCover,
      //   }),
      //   120,
      //   120
      // ),
      video: data.articleVideo?env.xhrPrefix + "/user/sysStorage/getFile/" + data.articleVideo+"?id="+data.articleVideo:null,
      // video: string(data.articleVideo)
      //   ? mergeURL(() => data.articleVideoSysStorage.objPath, {
      //       id: data.articleVideo,
      //     })
      //   : "",
      title: string(data.articleTitle),
      summary: string(data.articleAbstract),
      content: string(() => data.articleIdArticleContentList[0].content),
      referer: string(data.articleSource),
      source: string(data.sourceLink),
      author: string(data.articleAuthor),
      editor: string(data.articleEditor),
      tags: array(data.articleTagMappArticleTagMapList)
        .filter((data) => string(data.parentId))
        .map((data) => this.formatArticleOfTag(data)),
      tag: this.formatArticleOfTag(
        object(
          () =>
            array(data.articleTagMappArticleTagMapList).filter((data) =>
              string(data.parentId)
            )[0]
        )
      ),
      startTime: int(data.startTime) ? new Date(int(data.startTime)).formatDate('yyyy-MM-dd') : null,
      publishTimeStr: int(data.publishTime) ? new Date(int(data.publishTime)).formatDate('yyyy-MM-dd hh:mm:ss') : null,
      publishTime: data.publishTime,
      startAt: toTimeString(int(data.startTime), "Y年M月D日"),
      endTime: int(data.endTime),
      endAt: toTimeString(int(data.endTime), "Y年M月D日"),
      weight: int(data.articleWeight),
      views: int(data.articleHits),
      clientRoleToPush: "",
      published: findValue(
        env.articlePublisheds,
        "id",
        string(data.articlePublish),
        "value",
        ""
      ),
      publishedText: findValue(
        env.articlePublisheds,
        "id",
        string(data.articlePublish),
        "name",
        ""
      ),
      createdAt: toTimeString(int(data.createdTime), "Y年M月D日 hh:mm"),
      isTop:data.isTop
    };
  },
  async getArticles(form = {}) {
    var publishTime = form.publishTime
    if(typeof form.publishTime === 'string'){
      publishTime = new Date(publishTime)
    }
    let res = await this.post("/articles.get", {
      articleTitle_exp:
        isString(form.title) && form.title
          ? [{ exp: "like", value: form.title }]
          : null,
      articleSource_exp:
        isString(form.referer) && form.referer
          ? [{ exp: "like", value: form.referer }]
          : null,
      articleAuthor_exp:
        isString(form.author) && form.author
          ? [{ exp: "like", value: form.author }]
          : null,
      publishTimeStart:form.publishTime?publishTime.getTime():null,
      publishTimeEnd:form.publishTime?publishTime.getTime()+1000*60*60*24-1:null,
      tagId_exp: [
        {
          exp: "==",
          value:
            isString(form.tagId) && form.tagId
              ? form.tagId
              : findValue(env.articleTypes, "value", form.type, "id", "666"),
        },
      ],
      articlePublish: findValue(
        env.articlePublisheds,
        "value",
        form.published,
        "id"
      ),
      isTop:form.isTop,
      orderBy: [
        { order: "publishTime", by: "desc" },
        { order: "articleWeight", by: "desc" },
        { order: "updateTime", by: "desc" },
        { order: "articleId", by: "desc" },
      ],
      pageSize: isNumber(form.linage) ? form.linage : 10,
      pageNum: isNumber(form.page) ? form.page : 1,
    });
    let data = object(res.data);
    if (res.code === 0)
      res.data = {
        list: array(data.list).map((data) => this.formatArticle(data)),
        linage: Math.max(int(data.pageSize), 1),
        page: Math.max(int(data.pageNum), 1),
        total: Math.max(int(data.numberOfElements), 0),
      };
    return res;
  },
  async addArticle(form = {}) {
    let res = await this.post("/article.add", {
      articleCover: string(getURLQuery(form.banner).id),
      articleVideo: string(getURLQuery(form.video).id),
      articleTitle: string(form.title),
      articleAbstract: string(form.summary),
      articleContent: string(form.content),
      articleSource: string(form.referer),
      sourceLink: string(form.source),
      articleAuthor: string(form.author),
      articleEditor: string(form.editor),
      articleTagIds: (() => {
        let typeId = findValue(env.articleTypes, "value", form.type, "id", "");
        let tagId = string(() => form.tag.id);
        return tagId ? [typeId, tagId].join() : typeId;
      })(),
      startTime: int(form.startTime),
      endTime: int(form.endTime),
      articleWeight: int(form.weight),
      articlePublish: findValue(
        env.articlePublisheds,
        "value",
        form.published,
        "id",
        ""
      ),
      publishTime: form.publishTime,
      isTop:form.isTop
    });
    if (res.code === 0) res.data = string(res.data);
    return res;
  },
  async getArticle(articleId) {
    let res = await this.post("/article.get", { articleId: string(articleId) });
    if (res.code === 0) res.data = this.formatArticle(res.data);
    return res;
  },
  async setArticle(form = {}) {
    let res = await this.post("/article.set", {
      articleId: string(form.id),
      articleCover: string(getURLQuery(form.banner).id),
      articleVideo: string(getURLQuery(form.video).id),
      articleTitle: string(form.title),
      articleAbstract: string(form.summary),
      articleContent: string(form.content),
      articleSource: string(form.referer),
      sourceLink: string(form.source),
      articleAuthor: string(form.author),
      articleEditor: string(form.editor),
      startTime: string(form.startTime),
      publishTime: string(form.publishTime),
      articleTagIds: (() => {
        let typeId = findValue(env.articleTypes, "value", form.type, "id", "");
        let tagId = string(() => form.tag.id);
        return tagId ? [typeId, tagId].join() : typeId;
      })(),
      articleWeight: int(form.weight),
      articlePublish: findValue(
        env.articlePublisheds,
        "value",
        form.published,
        "id",
        ""
      ),
      isTop: form.isTop
    });
    if (res.code === 0) {
    }
    return res;
  },
  async delArticle(...articles) {
    let res = await this.post("/article.del", {
      ids: articles.map((article) => article.id).join(),
    });
    if (res.code === 0) {
    }
    return res;
  },
  async pushArticle(articleId, clientRole) {
    let res = await this.post("/article.push", {
      articleId: string(articleId),
      userRole: findValue(env.userRoles, "value", string(clientRole), "id"),
    });
    if (res.code === 0) {
    }
    return res;
  },
  async getStatsOrderCity(form = {}) {
    let res = await this.post("/stats/order-city.get", {
      areaId: isString(form.cityId) && form.cityId ? form.cityId : null,
      startTime: int(form.startTime) > 0 ? int(form.startTime) : null,
      endTime: int(form.endTime) > 0 ? int(form.endTime) : null,
    });
    if (res.code === 0) res.data = array(res.data);
    return res;
  },
  async getcountryList(params) {
    let res = await this.post("app/statisticsV3/statisticsOrderCounty", {
      fwxz: params.fwxz || "",
      tagId: params.tagId || "",
      countyId: params.areaId || "",
      pageNum: params.pageNum,
      pageSize: params.pageSize,
      status: params.status || "",
    });

    return res;
  },
  async getcountryListciiy(params) {
    let res = await this.post("app/big/data/completion/area/detail", {
      fwxz: params.fwxz || "",
      tagId: params.tagId || "",
      countyId: params.areaId || "",
      pageNum: params.pageNum,
      pageSize: params.pageSize,
      status: params.status || "",
      level: params.level || "",
      startTime: params.startTime,
      endTime: params.endTime
    });

    return res;
  },
  async getcountryListnumtag(params) {
    let res = await this.post("app/big/data/completion/tag/detail", {
      fwxz: params.fwxz || "",
      tagId: params.tagId || "",
      countyId: params.areaId || "",
      pageNum: params.pageNum,
      pageSize: params.pageSize,
      status: params.status || "",
      startTime:params.year?new Date(params.year,0,1).getTime():null,
      endTime: params.year?new Date(params.year+'-12-31 23:59:59').getTime():null
    });

    return res;
  },
  async getcountryListnum(params) {
    let res = await this.post("app/big/data/completion/fwxz/detail", {
      fwxz: params.fwxz || "",
      tagId: params.tagId || "",
      countyId: params.areaId || "",
      pageNum: params.pageNum,
      pageSize: params.pageSize,
      status: params.status || "",
    });

    return res;
  },

  async getstatisticsOrderFwxz() {
    let res = await this.post("/app/statisticsV3/statisticsOrderFwxz", {});

    return res;
  },
  async getgroupranking(form = {}) {
    let res = await this.post("/app/big/data/completion/fwxz", {
      startTime: int(form.startTime) > 0 ? int(form.startTime) : 1685631599000,
      endTime: int(form.endTime) > 0 ? int(form.endTime) : 1985631599000,
      pageSize: 100,
      pageNum: 1,
    });

    return res;
  },
  async getstatisticsOrderFwxznum(data) {
    let res = await this.post("/app/big/data/completion/fwxz", {...data});

    return res;
  },
  async getStatsLiveCity(form = {}) {
    let res = await this.post("/user/liveness/statistics", {
      areaId: isString(form.cityId) && form.cityId ? form.cityId : null,
      startTime: int(form.startTime) > 0 ? int(form.startTime) : null,
      endTime: int(form.endTime) > 0 ? int(form.endTime) : null,
      userRole: form.userRole,
      type: form.activityType,
    });
    if (res.code === 0) res.data = array(res.data);
    return res;
  },
  async getStatsOrderTeam(form = {}) {
    let res = await this.post("/stats/order-team.get", {
      deptType_exp: [{ exp: "in", value: "1,2" }],
      provinceId: "450000",
      cityId: isString(form.cityId) && form.cityId ? form.cityId : null,
      startTime: int(form.startTime) > 0 ? int(form.startTime) : null,
      endTime: int(form.endTime) > 0 ? int(form.endTime) : null,
      orderBy: [
        { order: "deptSort", by: "desc" },
        { order: "deptId", by: "asc" },
      ],
      pageSize: 1000,
      pageNum: 1,
    });
    if (res.code === 0) res.data = array(res.data);
    return res;
  },
  async getStatsOrderGovernment(form = {}) {
    let res = await this.post("/stats/order-government.get", {
      deptType: "3",
      provinceId: "450000",
      cityId: string(form.cityId) || null,
      areaId: string(form.areaId) || null,
      // areaId_exp: [{ exp: "isNull", value: "666" }],
      startTime: int(form.startTime) > 0 ? int(form.startTime) : null,
      endTime: int(form.endTime) > 0 ? int(form.endTime) : null,
      orderBy: [
        { order: "deptSort", by: "desc" },
        { order: "deptId", by: "asc" },
      ],
      pageSize: 10000,
      pageNum: 1,
    });
    if (res.code === 0) res.data = array(res.data);

    return res;
  },

  async getStatsOrderGovernmentBelong(form = {}) {
    let res = await this.post("/app/statisticsV3/district/epartmentStaBelongDept", {
      startTime: int(form.startTime) > 0 ? int(form.startTime) : null,
      endTime: int(form.endTime) > 0 ? int(form.endTime) : null,
      pageSize: 10000,
      pageNum: 1,
    });
    if (res.code === 0) res.data = array(res.data);
    return res;
  },
  async exportStatsOrderGovernmentBelong(form = {}) {
    let res = await this.post("/admin/export/exportWorkOrderGovTingList", {
      startTime: int(form.startTime) > 0 ? int(form.startTime) : null,
      endTime: int(form.endTime) > 0 ? int(form.endTime) : null,
      pageSize: 10000,
      pageNum: 1,
    });
    if (res.code === 0) res.data = array(res.data);
    return res;
  },
  /**
   * 返回区域
   * @param form
   * @return {Promise<{msg, code: *, data: *}>}
   */
  async getStatsOrderGovernmentBelongArea(form = {}) {
    let res = await this.post("/app/statisticsV3/district/epartmentStaBelongArea", {
      deptId: string(form.deptId) || null,
      startTime: int(form.startTime) > 0 ? int(form.startTime) : null,
      endTime: int(form.endTime) > 0 ? int(form.endTime) : null,
      pageSize: 10000,
      pageNum: 1,
    });
    if (res.code === 0) res.data = array(res.data);
    return res;
  },

  /**
   * 统计部门-返回市级、区县
   * @param form
   * @return {Promise<{msg, code: *, data: *}>}
   */
  async getStatsOrderDeptBackArea(form = {}) {
    let res = await this.post("/app/statisticsV3/district/epartmentStaArea", {
      deptType: "3",
      cityId: string(form.cityId) || null,
      startTime: int(form.startTime) > 0 ? int(form.startTime) : null,
      endTime: int(form.endTime) > 0 ? int(form.endTime) : null,
    });
    if (res.code === 0) res.data = array(res.data);
    return res;
  },

  /**
   * 统计部门-返回部门
   * @param form
   * @return {Promise<{msg, code: *, data: *}>}
   */
  async getStatsOrderDeptBackDept(form = {}) {
    let res = await this.post("/app/statisticsV3/district/epartmentStaDept", {
      deptType: "3",
      areaId: string(form.areaId) || null,
      startTime: int(form.startTime) > 0 ? int(form.startTime) : null,
      endTime: int(form.endTime) > 0 ? int(form.endTime) : null,
    });
    if (res.code === 0) res.data = array(res.data);
    return res;
  },

  async getStatsOrderTag(form = {}) {
    let res = await this.post("/stats/order-tag.get", {
      startTime: int(form.startTime) > 0 ? int(form.startTime) : null,
      endTime: int(form.endTime) > 0 ? int(form.endTime) : null,
      orderBy: [
        { order: "tagSort", by: "desc" },
        { order: "tagId", by: "desc" },
      ],
      pageSize: 1000,
      pageNum: 1,
    });
    if (res.code === 0) res.data = array(res.data);
    return res;
  },
  async getStatsOrderTagnum(form = {}) {
    let res = await this.post("/app/big/data/completion/tag", {
      startTime: int(form.startTime) > 0 ? int(form.startTime) : null,
      endTime: int(form.endTime) > 0 ? int(form.endTime) : null,
      orderBy: [
        { order: "tagSort", by: "desc" },
        { order: "tagId", by: "desc" },
      ],
      pageSize: 1000,
      pageNum: 1,
    });
    if (res.code === 0) res.data = array(res.data);
    return res;
  },
  async getStatsAttendanceTeam(form = {}) {
    let res = await this.post("/stats/attendance-team.get", {
      deptType_exp: [{ exp: "in", value: "1,2" }],
      provinceId: "450000",
      cityId: isString(form.cityId) && form.cityId ? form.cityId : null,
      startTime: int(form.startTime) > 0 ? int(form.startTime) : null,
      endTime: int(form.endTime) > 0 ? int(form.endTime) : null,
      orderBy: [
        { order: "deptSort", by: "desc" },
        { order: "deptId", by: "asc" },
      ],
      pageSize: 1000,
      pageNum: 1,
    });
    if (res.code === 0) res.data = array(res.data);
    return res;
  },
  async getStatsEvaluationTeam(form = {}) {
    let res = await this.post("/stats/evaluation-team.get", {
      deptType_exp: [{ exp: "in", value: "1,2" }],
      provinceId: "450000",
      cityId: isString(form.cityId) && form.cityId ? form.cityId : null,
      startTime: int(form.startTime) > 0 ? int(form.startTime) : null,
      endTime: int(form.endTime) > 0 ? int(form.endTime) : null,
      orderBy: [
        { order: "deptSort", by: "desc" },
        { order: "deptId", by: "asc" },
      ],
      pageSize: 1000,
      pageNum: 1,
    });
    if (res.code === 0) res.data = array(res.data);
    return res;
  },
  async getStatsEvaluationGovernment(form = {}) {
    let res = await this.post("/stats/evaluation-government.get", {
      deptType: "3",
      provinceId: "450000",
      cityId: string(form.cityId) || null,
      areaId_exp: [{ exp: "isNull", value: "666" }],
      startTime: int(form.startTime) > 0 ? int(form.startTime) : null,
      endTime: int(form.endTime) > 0 ? int(form.endTime) : null,
      orderBy: [
        { order: "deptSort", by: "desc" },
        { order: "deptId", by: "asc" },
      ],
      pageSize: 10000,
      pageNum: 1,
    });
    if (res.code === 0) res.data = array(res.data);
    return res;
  },
  async getStatsArticlePolicy(form = {}) {
    let res = await this.post("/stats/article-policy.get", {
      parentId: "2",
      startTime: int(form.startTime) > 0 ? int(form.startTime) : null,
      endTime: int(form.endTime) > 0 ? int(form.endTime) : null,
      orderBy: [
        { order: "tagSort", by: "desc" },
        { order: "tagId", by: "desc" },
      ],
      pageSize: 100,
      pageNum: 1,
    });
    if (res.code === 0) res.data = array(res.data);
    return res;
  },
  async getStatsArticleSjwt(form = {}) {
    let res = await this.post("/app/statisticsV3/district/zbtb1", {
      parentId: "2",
      startTime: int(form.startTime) > 0 ? int(form.startTime) : null,
      endTime: int(form.endTime) > 0 ? int(form.endTime) : null,
      orderBy: [
        { order: "tagSort", by: "desc" },
        { order: "tagId", by: "desc" },
      ],
      pageSize: 100,
      pageNum: 1,
    });
    if (res.code === 0) res.data = array(res.data);
    return res;
  },
  async getStatsArticleQqdy(form = {}) {
    let res = await this.post("/app/statisticsV3/district/zbtb2", {
      parentId: "2",
      startTime: int(form.startTime) > 0 ? int(form.startTime) : null,
      endTime: int(form.endTime) > 0 ? int(form.endTime) : null,
      orderBy: [
        { order: "tagSort", by: "desc" },
        { order: "tagId", by: "desc" },
      ],
      pageSize: 100,
      pageNum: 1,
    });
    if (res.code === 0) res.data = array(res.data);
    return res;
  },
  async getStatsArticleSxdy(form = {}) {
    let res = await this.post("/app/statisticsV3/district/zbtb2sx", {
      parentId: "2",
      startTime: int(form.startTime) > 0 ? int(form.startTime) : null,
      endTime: int(form.endTime) > 0 ? int(form.endTime) : null,
      orderBy: [
        { order: "tagSort", by: "desc" },
        { order: "tagId", by: "desc" },
      ],
      pageSize: 100,
      pageNum: 1,
    });
    if (res.code === 0) res.data = array(res.data);
    return res;
  },
  async getStatsArticleGzzb(form = {}) {
    let res = await this.post("/app/statisticsV3/district/zbtb3", {
      parentId: "2",
      startTime: int(form.startTime) > 0 ? int(form.startTime) : null,
      endTime: int(form.endTime) > 0 ? int(form.endTime) : null,
      orderBy: [
        { order: "tagSort", by: "desc" },
        { order: "tagId", by: "desc" },
      ],
      pageSize: 100,
      pageNum: 1,
    });
    if (res.code === 0) res.data = array(res.data);
    return res;
  },
  async getStatsArticleGzzbV2(form = {}) {
    let res = await this.post("/app/statisticsV3/district/v2/zbtb3", {
      parentId: "2",
      startTime: int(form.startTime) > 0 ? int(form.startTime) : null,
      endTime: int(form.endTime) > 0 ? int(form.endTime) : null,
      orderBy: [
        { order: "tagSort", by: "desc" },
        { order: "tagId", by: "desc" },
      ],
      pageSize: 100,
      pageNum: 1,
    });
    if (res.code === 0) res.data = array(res.data);
    return res;
  },

  async getStatsArticleQjhb(form = {}) {
    let res = await this.post("/app/statisticsV3/district/zbtb4", {
      parentId: "2",
      startTime: int(form.startTime) > 0 ? int(form.startTime) : null,
      endTime: int(form.endTime) > 0 ? int(form.endTime) : null,
      orderBy: [
        { order: "tagSort", by: "desc" },
        { order: "tagId", by: "desc" },
      ],
      pageSize: 100,
      pageNum: 1,
    });
    if (res.code === 0) res.data = array(res.data);
    return res;
  },
  async init() {
    let profile = this.profile;
    if (profile) return { code: 0, data: profile };
    let res = await this.getUserProfile();
    if (res.code === 0) {
      res.data.nodes.map((node) => {
        if(node.name == '专班热线'){
          node.access = true
        }})
      await this.getProvinces();
      await this.getCitys();
      await this.getCountys();
      return res;
    } else {
      return { code: 2 };
    }
  },

  async policyGets(form = {}) {
    let res = await this.post("/admin/policy/policyList", {
      policyTitle_exp:
        isString(form.title) && form.title
          ? [{ exp: "like", value: form.title }]
          : null,
      orderBy: [
        { order: "createTime", by: "desc" },
        { order: "policyId", by: "desc" },
      ],
      pageSize: isNumber(form.linage) ? form.linage : 10,
      pageNum: isNumber(form.page) ? form.page : 1,
    });
    let data = object(res.data);
    if (res.code === 0)
      res.data = {
        list: array(data.list).map((data) => this.policyFormat(data)),
        linage: Math.max(int(data.pageSize), 1),
        page: Math.max(int(data.pageNum), 1),
        total: Math.max(int(data.numberOfElements), 0),
      };
    return res;
  },
  async policyAdd(form = {}) {
    let res = await this.post("/admin/policy/policyAdd", {
      ...form,
      policyTitle: string(form.title),
      policyNo: string(form.no),
      policyContent: string(form.content),
    });
    if (res.code === 0) res.data = string(res.data);
    return res;
  },
  async policyDel(...policys) {
    let res = await this.post("/admin/policy/policyDelete", {
      ids: policys.map((policy) => policy.policyId).join(),
    });
    if (res.code === 0) {
    }
    return res;
  },
  async policyGet(policyId) {
    let res = await this.post("/admin/policy/policyGet", { policyId: string(policyId) });
    if (res.code === 0) res.data = this.policyFormat(res.data);
    return res;
  },
  async policySet(form = {}) {
    let res = await this.post("/admin/policy/policyEdit", {
      ...form,
      policyTitle: string(form.policyTitle),
      policyNo: string(form.policyNo),
      policyContent: string(form.policyContent),
    });
    if (res.code === 0) {
    }
    return res;
  },
  policyFormat: (data = {}) => {
    return {
      ...data,
      publishTimeStr: string(data.publishTime)?new Date(eval(data.publishTime)).formatDate("yyyy-MM-dd HH"):"",
    }
  },


  async sysFeedbackGets(form = {}) {
    let res = await this.post("/admin/feedback/list", {
      feedbackTimeStart: form.startTime,
      feedbackTimeEnd: form.endTime,
      isAdmin:'true',
      pageSize: isNumber(form.linage) ? form.linage : 10,
      pageNum: isNumber(form.page) ? form.page : 1,
    });
    let data = object(res.data);
    if (res.code === 0)
      res.data = {
        list: array(data.list).map((data) => {
          return {
            ...data,
            feedbackTimeStr: string(data.feedbackTime)?new Date(eval(data.feedbackTime)).formatDate("yyyy-MM-dd HH:mm:ss"):''
          }
        }),
        linage: Math.max(int(data.pageSize), 1),
        page: Math.max(int(data.pageNum), 1),
        total: Math.max(int(data.numberOfElements), 0),
      };
    return res;
  },
  async sysFeedbackReply(form = {}) {
    let res = await this.post("/admin/feedback/reply", {
      ...form
    });
    return res;
  },

};
